Python - how to print amount of numbers, periods, and commas in file

Python——如何打印数字,时间,和逗号分隔文件

Tags: python
标签: python

问题 (Question)

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")

Basically it will show the number of lines and the number of words, but I can't get it to show the number of numbers, commas, and dots. I have it read a file that the user enters and then show the amount of lines and words, but for some reason it says 0 for numbers commas and dots. I commented out the part where it gave me trouble. If i remove the comma then i just get an error. thanks guys

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数字逗号和点。我注释掉的部分给我麻烦。如果我删除逗号然后我只是得到一个错误。谢谢你们

最佳答案 (Best Answer)

For the punctuations, why not just do:

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

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

欢歌,为什么不做:

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

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

答案 (Answer) 2

This code loops over every character in each line, and adds 1 to its variable:

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))

Testing it out:

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 

Running:

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

Everything makes sense here, except the lineCount the reason why this is 6 is because of newlines. In my editor (nano), it adds a newline to the end of any file by default. So just imagine the text file to be this:

>>> 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
>>> 

Hope this helps!

这段代码循环遍历每个角色在每一行,并添加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是因为换行。在我的编辑器(纳米),它添加了一个换行符的默认任何文件。所以想象一下文本文件:

>>> 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
>>> 

希望这可以帮助!

答案 (Answer) 3

You could use the Counter class to take care of it you:

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['.']))

您可以使用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['.']))

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23452167