尝试使用一个函数的输出来影响下一个函数来计算文本文件中的单词

Trying to use output of one function to influence the next function to count words in text file

我正在尝试使用一个函数来计算文本文件中的单词数,在此文本文件 "cleaned" 仅包含字母和单个空格之后。所以我有我的第一个函数,我想清理文本文件,然后我有我的下一个函数实际上 return 前一个函数结果的长度 (清理文本)。这是这两个函数。

def cleanUpWords(file):
    words = (file.replace("-", " ").replace("  ", " ").replace("\n", " "))
    onlyAlpha = ""
    for i in words:
        if i.isalpha() or i == " ":
            onlyAlpha += i
    return onlyAlpha

所以 words 是清理后的文本文件,没有双空格、连字符、换行符。 然后,我取出所有数字,然后 return 清理的 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())

我在 main() 中定义的 newWords,其中 `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.")

希望我提供了足够的信息。

问题很简单:你把它分成了两个函数,但是你完全忽略第一个函数的结果,而是计算单词的数量清理之前!

将您的 main 函数更改为此,然后它应该可以工作。

def main():
    harper = readFile("Harper's Speech.txt")
    newWords = cleanUpWords(harper)
    print(numWords(newWords), "Words.") # use newWords here!

此外,您的 cleanUpWords 功能还可以改进一下。它仍然可以在文本中留下双倍或三倍的 spaces,你也可以让它更短一些。或者,您可以使用正则表达式:

import re
def cleanUpWords(string):
    only_alpha = re.sub("[^a-zA-Z]", " ", string)
    single_spaces = re.sub("\s+", " ", only_alpha)
    return single_spaces

或者您可以先过滤掉所有非法字符,然后将单词拆分并用单个 space.

将它们拼接起来
def cleanUpWords(string):
    only_alpha = ''.join(c for c in string if c.isalpha() or c == ' ')
    single_spaces = ' '.join(only_alpha.split())
    return single_spaces

示例,您的原始函数将为此保留一些双 spaces:

>>> s = "text with    triple spaces and other \n sorts \t of strange ,.-#+ stuff and 123 numbers"
>>> cleanUpWords(s)
text with triple spaces and other sorts of strange stuff and numbers

(当然,如果你打算反正拆分的话,双space是没有问题的。)