2015-12-03 826 views
0

这里是我的代码计数从文本文件中每行字数在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)) 

目前,我的程序只计算运行总计字的文本文件,但我希望它仅计算每行字的文件。另外,我希望程序在最后分析文本文件,并打印出诸如“一行中的大多数单词”和“每行的平均单词”等内容,但我无法使用当前的格式进行操作。任何帮助将不胜感激。

+0

您正在执行累计加法操作'wordCount = wordCount + len(f1)'..当然您会在最后得到总计 –

+0

另请参阅:[计算文本文件中的行数,字数和字符数使用Python](http://stackoverflow.com/questions/4783899/counting-lines-words-and-characters-within-a-text-file-using-python) –

回答

1

就快,只需要添加几件事情:

lines=0 
wordCount=0 
mostWordsInLine = 0 
fileHandler=getInputFile() 


for lineOfText in fileHandler.readlines(): 
    lines += 1 
    print(str(lines),str(lineOfText)) 
    f1=lineOfText.split() 
    wordCount=wordCount+len(f1) 
    if len(f1) > mostWordsInLine: 
     mostWordsInLine = len(f1) 
    print ("Word count:" +str(wordCount)) 

print "Average words per line: {}".format(wordCount/lines) 
print "Most words in a single line: {}".format(mostWordsInLine) 

编辑:为了打印出每行字的#,你可以更改for循环内的print声明。

目前你在做print ("Word count:" +str(wordCount)),它打印出累计总数。只需将其更改为print 'Word count: {}'.format(len(f1))

+0

谢谢,但我仍然无法计算每行中的单词;它仍然只是保持累计总数。 –

+0

@AButler - 如果你想保留每一行的字数统计记录,你最好用下面答案中的解决方案。 – TigerhawkT3

+0

@AButler编辑回复以解决该情况。 – dursk

1

创建list出来的:

result = [len(line.split()) for line in fileHandler] 

然后你可以找到总字数:

print(sum(result)) 

字数每行:

print(*result, sep='\n') 

最高字数:

print(max(result)) 

平均字数:

print(sum(result)/len(result)) 

如果你也想保存每一行,先读:

lines = fileHandler.readlines() 

然后算的话:

result = [len(line.split()) for line in lines] 

然后zip()这两个list s:

print(*('{} -- {}'.format(*item) for item in zip(lines, results)), sep='\n') 
+0

我感谢帮助。打印出每行后,是否有任何方法可以打印每行的字数? –

+0

@AButler - 你应该保存文件内容,然后,如我编辑的答案中所示。 – TigerhawkT3

+0

因为'split'默认情况下会在空白处分裂,所以不会精确计算单词。例如'some-sentence'会导致长度为3. –

相关问题