为什么这不打印所有内容,而仅显示文件中的单词总数?

时间:2018-08-21 12:41:34

标签: 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 """

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

不确定为什么需要全局fo。如果您能解释,我将调整我的代码。

这是我的版本

class text_reader():

    # for opening of file
    def __init__(self,file_name):
        self.file_name = file_name
        self.content = open(file_name,"r").read()

    # for counting no of words in a file
    def wordcount(self):
        print("Number of words:")
        print(len(self.content.split()))

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

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


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 """