Python - 如何在文件中打印数字,句点和逗号的数量

时间:2014-05-04 03:05:47

标签: python

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

with open(fileName, 'r') as f:
    for line in f:
        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
                # elif text == ",":
                    # comCount += 1
                # elif text == ".":
                    # dotCount += 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")

基本上它会显示行数和单词数,但我无法显示数字,逗号和点的数量。我让它读取用户输入的文件,然后显示行数和单词数,但由于某种原因,它表示数字逗号和点数为0。我评论了它给我带来麻烦的部分。如果我删除逗号然后我只是得到一个错误。谢谢你们

3 个答案:

答案 0 :(得分:0)

对于标点符号,为什么不这样做:

def showCounts(fileName):
    ...
    ...
    with open(fileName, 'r') as fl:
        f = fl.read()

    comCount = f.count(',')
    dotCount = f.count('.')

答案 1 :(得分:0)

此代码循环遍历每一行中的每个字符,并将1加到其变量中:

numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0

fileName = 'test.txt'

with open(fileName, 'r') as f:
    for line in f:
        wordCount+=len(line.split())
        lineCount+=1
        for char in line:
            if char.isdigit() == True:
                numCount+=1
            elif char == '.':
                dotCount+=1
            elif char == ',':
                commaCount+=1

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

测试一下:

test.txt

Hello, my name is B.o.b. I like biking, swimming, and running.

I am 125 years old, and  I was 124 years old 1 year ago.

Regards,
B.o.b 

<强>运行:

bash-3.2$ python count.py
Number count: 7
Comma count: 5
Dot  count: 7
Line count: 6
Word count: 27
bash-3.2$ 

这里的一切都有意义,除了lineCount之所以这是6是因为新行。在我的编辑器( nano )中,默认情况下它会在任何文件的末尾添加换行符。所以想象一下文本文件:

>>> x = open('test.txt').read()
>>> x
'Hello, my name is B.o.b. I like biking, swimming, and running.\n\nI am 125 years old, and  I was 124 years old 1 year ago.\n\nRegards,\nB.o.b \n'
>>> x.count('\n')
6
>>> 

希望这有帮助!

答案 2 :(得分:0)

你可以使用Counter班来照顾你:

from collections import Counter

with open(fileName, 'r') as f:
    data    = f.read().strip()
    lines   = len(data.split('\n'))
    words   = len(data.split())
    counts  = Counter(data)
    numbers = sum(v for (k,v) in counts.items() if k.isdigit())

print("Line count: {}".format(lines))
print("Word count: {}".format(words))
print("Number count: {}".format(numbers))
print("Comma count: {}".format(counts[',']))
print("Dot count: {}".format(counts['.']))