python - 为什么这不打印所有内容而只给出文件中的总字数?

标签 python

为什么我没有得到想要的结果,而只得到文件中的字数? 我还应该获得一个不重复的单词列表以及文件的完整内容。

class text_reader:

# for opening of file
    def __init__(self,file_name):
        global fo
        self.file_name = file_name
        fo=open(file_name,"r")
# for counting no of words in a file
    def wordcount(self):
        num_word=0
        for line in fo:
            words = line.split()
            num_word=num_word + len(words)
        print("Number of words:")
        print(num_word)

# for printing the content of a file   
    def display(self):
        contents = fo.read()
        print(contents)

# for printing list of words in a file and words should not be repeated
    def wordlist(self):
        for x in fo:
            word = x.split()
            list=word.set()
            print(list)



t = text_reader("C:/Users/ALI/Desktop/article.txt")
t.wordcount()
t.display()
t.wordlist()


# article.txt

"""PYTHON IS AN INTERPRETED HIGH-LEVEL PROGRAMMING LANGUAGE FOR GENERAL- 
PURPOSE PROGRAMMING. CREATED BY GUIDO VAN ROSSUM AND FIRST RELEASED IN 1991,
PYTHON HAS A DESIGN PHILOSOPHY THAT EMPHASIZES CODE READABILITY, NOTABLY 
USING SIGNIFICANT """

最佳答案

fo 对象有一个内部指针,它指向 python 应开始读取文件的位置。调用 fo.read() 后,它现在指向文件的末尾(即 python 完成读取的位置)。因此,对 fo.read() 的后续调用现在将从文件的末尾开始,因此返回一个空字符串。

您需要将指针重置到文件的开头,或者在构造函数中调用一次fo.read()并保存结果。

关于python - 为什么这不打印所有内容而只给出文件中的总字数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948922/

相关文章:

python - 在 Pandas 中使用变量进行查询

python - Python GC 也会关闭文件吗?

python - python中类继承Generic的目的是什么?

python - 在将包上传到 pypicloud 之前更新 setup.py 中的版本

python - 获取字典中的最大值

python - 在一行中将数​​字减半

python - Heroku 数据库 : Insert operation

python - Django 错误 "add a non-nullable field"

python - 为什么 python dict 键/值不像鸭子一样嘎嘎叫?

python - 如何将命令行参数从 oc start-build 传递到 dockerfile 以在 dockerfile 内设置环境变量