Python我读了一个文件,但它显示了错误的值?

2024-05-18 19:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

def showCounts(fileName):
    lineCount = 0
    wordCount = 0
    numCount = 0
    comCount = 0
    dotCount = 0

    with open(fileName, 'r') as f:
        for line in f:
            for char in line:
                if char.isdigit() == True:
                    numCount+=1
                elif char == '.':
                    dotCount+=1
                elif char == ',':
                    comCount+=1
#i know formatting below looks off but it's right
            words = line.split()
            lineCount += 1
            wordCount += len(words)

            for word in words:
#                text = word.translate(string.punctuation)
                exclude = set(string.punctuation)
            text = ""
            text = ''.join(ch for ch in text if ch not in exclude)
            try:
                if int(text) >= 0 or int(text) < 0:
                    numCount += 1
            except ValueError:
                pass

print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
print("Number count: " + str(numCount))
print("Comma count: " + str(comCount))
print("Dot  count: " + str(dotCount) + "\n")

我让它读取一个包含单词、行、点、逗号和数字的.txt文件。它会给我正确的点数,逗号和数字,但是单词和行的值会比实际值高很多。有人知道为什么吗?谢谢你们。你知道吗


Tags: textinforifcountlinewordcountwords
1条回答
网友
1楼 · 发布于 2024-05-18 19:14:37

我不知道这是否真的是答案,但我的声誉还不足以发表评论,所以我把它放在这里。如果它不能解决问题,你显然不需要接受它作为最终答案。你知道吗

所以,我认为这可能与所有的print语句实际上都在showCounts()函数之外有关。尝试缩进print语句。你知道吗

我希望这有帮助。你知道吗

相关问题 更多 >

    热门问题