Python 计算文件中的字数时出现运行时错误

Python Runtime error counting words in file

在一段时间内遇到语法错误并意识到我犯了一个愚蠢的错误后,我继续纠正我的方式,结果却遇到了运行时错误。到目前为止,我正在尝试制作一个能够从文件中读取单词数量的程序,但是,该程序似乎没有计算单词数量,而是计算字母数量,这对我的结果没有好处程序。请在下面找到合适的代码。感谢所有贡献!

def GameStage02():
global FileSelection                                                                                                                                                                           
global ReadFile
global WordCount
global WrdCount
FileSelection = filedialog.askopenfilename(filetypes=(("*.txt files", ".txt"),("*.txt files", "")))
with open(FileSelection, 'r') as file:
    ReadFile = file.read()
SelectTextLabel.destroy()                                                                                                                                             
WrdCount=0
for line in ReadFile:
    Words=line.split()
    WrdCount=WrdCount+len(Words)
    print(WrdCount)
GameStage01Button.config(state=NORMAL)

让我们分解一下:

ReadFile = file.read() 会给你一个字符串。

for line in ReadFile 将遍历该字符串中的字符。

Words=line.split() 会给你一个包含一个或零个字符的列表。

这可能不是您想要的。变化

ReadFile = file.read()

ReadFile = file.readlines()

这将为您提供一个行列表,您可以将其迭代 and/or split 到单词列表中。

此外,请注意 file 不是一个好的变量名(在 Python2 中),因为它已经是一个内置的名称。

作为 的延续,这里有一段代码可以执行此操作:

import re
#open file.txt, read and 
#split the file content with \n character as the delimiter(basically as lines)
lines = open('file.txt').read().splitlines() 
count = 0
for line in lines:
  #split the line with whitespace delimiter and get the list of words in the line
  words = re.split(r'\s', line) 
  count += len(words)
print count