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