Python运行时计算文件中的单词时出错
在经历了一段明显的语法错误之后,意识到我犯了一个愚蠢的错误,我继续纠正我的方法,结果却遇到了一个运行时错误。到目前为止,我正在尝试制作一个能够从文件中读取字数的程序,然而,该程序似乎不是计算字数,而是计算字母数,这对我的程序的结果没有好处。请在下面找到相应的代码。感谢所有的贡献Python运行时计算文件中的单词时出错,python,file,runtime-error,word-count,Python,File,Runtime Error,Word Count,在经历了一段明显的语法错误之后,意识到我犯了一个愚蠢的错误,我继续纠正我的方法,结果却遇到了一个运行时错误。到目前为止,我正在尝试制作一个能够从文件中读取字数的程序,然而,该程序似乎不是计算字数,而是计算字母数,这对我的程序的结果没有好处。请在下面找到相应的代码。感谢所有的贡献 def GameStage02(): global FileSelection
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()
将为您提供一个字符串
ReadFile中的行的将迭代该字符串中的字符
Words=line.split()
那可能不是你想要的。改变
ReadFile = file.read()
到
这将为您提供一个行列表,您可以对其进行迭代和/或将其拆分为单词列表
此外,请注意,文件
不是一个好的变量名(在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
@阿利多布拉没问题(看,我也是一个流氓)。
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