这里是我的代码计数从文本文件中每行字数在Python
def getInputFile():
bad = True
while bad:
try:
fileName = input ("Enter file name: ")
# Open file for input
f = open(fileName, "r") # Note: "r" means open for reading.
bad = False
except Exception as err:
print ("Please enter a valid file name:")
return f
lines=0
wordCount=0
fileHandler=getInputFile()
for lineOfText in fileHandler.readlines():
lines += 1
print(str(lines),str(lineOfText))
f1=lineOfText.split()
wordCount=wordCount+len(f1)
print ("Word count:" +str(wordCount))
目前,我的程序只计算运行总计字的文本文件,但我希望它仅计算每行字的文件。另外,我希望程序在最后分析文本文件,并打印出诸如“一行中的大多数单词”和“每行的平均单词”等内容,但我无法使用当前的格式进行操作。任何帮助将不胜感激。
您正在执行累计加法操作'wordCount = wordCount + len(f1)'..当然您会在最后得到总计 –
另请参阅:[计算文本文件中的行数,字数和字符数使用Python](http://stackoverflow.com/questions/4783899/counting-lines-words-and-characters-within-a-text-file-using-python) –