【发布时间】:2015-06-05 08:14:28
【问题描述】:
在通过仅包含字母和单个空格来“清理”此文本文件之后,我正在尝试使用一个函数来计算文本文件中的单词数。所以我有我的第一个函数,我想清理文本文件,然后我有我的下一个函数来实际返回前一个函数结果的长度 (清理文本)。这是这两个函数。
def cleanUpWords(file):
words = (file.replace("-", " ").replace(" ", " ").replace("\n", " "))
onlyAlpha = ""
for i in words:
if i.isalpha() or i == " ":
onlyAlpha += i
return onlyAlpha
所以 words 是没有双空格、连字符、换行符的文本文件。 然后,我取出所有数字,然后返回清理后的 onlyAlpha 文本文件。 现在,如果我输入 return len(onlyAlpha.split()) 而不是 return onlyAlpha ...它会给我文件中正确的单词数量(我知道,因为我有答案)。但是如果我这样做,并尝试将它分成两个功能,它会搞砸单词的数量。这就是我要说的(这是我的字数统计功能)
def numWords(newWords):
'''Function finds the amount of words in the text file by returning
the length of the cleaned up version of words from cleanUpWords().'''
return len(newWords.split())
newWords 我在 main() 中定义,其中 `newWords = cleanUpWords(harper)-----harper 是一个运行另一个读取函数的变量(除此之外)。
def main():
harper = readFile("Harper's Speech.txt") #readFile function reads
newWords = cleanUpWords(harper)
print(numWords(harper), "Words.")
鉴于所有这些,请告诉我为什么如果我将其拆分为两个函数会给出不同的答案。
作为参考,这里是对单词进行计数,但不拆分单词清理和单词计数功能,numWords 现在清理和计数,不推荐。
def numWords(file):
'''Function finds the amount of words in the text file by returning
the length of the cleaned up version of words from cleanUpWords().'''
words = (file.replace("-", " ").replace(" ", " ").replace("\n", " "))
onlyAlpha = ""
for i in words:
if i.isalpha() or i == " ":
onlyAlpha += i
return len(onlyAlpha.split())
def main():
harper = readFile("Harper's Speech.txt")
print(numWords(harper), "Words.")
希望我提供了足够的信息。
【问题讨论】:
-
如我所料,快速测试从两种配方中得到了相同的结果。你能删掉文件处理部分并提供一个失败的示例输入吗?
标签: python file python-3.x io count