读取文件的项目,计算每个字母,评估每个字母的百分比

时间:2017-05-02 11:32:27

标签: python

我尝试了这些代码,但是它们没有正常工作。它是以垂直线显示文件而没有正确显示百分比我需要做什么呢?我只是按照我们的老师问我们但它没有工作

while Diceroll not in ('Y', 'N'):
    ...

1 个答案:

答案 0 :(得分:0)

所以这就是我实际编写这个程序的方法:

# Allows us to get a list of a-z.
import string
# Allows us to use an OrderedDict.
import collections

# Creates an OrderedDict (like a normal dict but maintains key order),
# with the keys a-z and the starting values of 0.
total_counts = collections.OrderedDict().fromkeys(list(string.ascii_lowercase),0)
# Counter for totally number of characters.
total_chars = 0

# Opens the file "file.txt" from the same directory as the script.
with open("file.txt", "r") as f:
    # Processes it line by line.
    for line in f:
        # Removes captialization.
        line = line.lower()
        # Processes each character in line.
        for c in line:
            # Checks if c is in a-z (and not say a space or puncutation).
            if c in total_counts:
                # Adds count to the specific character and the overall number.
                total_counts[c] += 1
                total_chars += 1

# Iterates the OrderdDict and prints the percentage.
for character, count in total_counts.iteritems():
    print("Count of the letter " + character + " is " + str(count) + "\t" + str(float(count)/total_chars*100))

正如您所看到的,我不会为每个字母编写ifprint语句,而是使用循环来最小化所需的代码。

大多数专栏都有评论,但如果您有任何问题请告诉我。

我也在Python3中写了这个并将其转换回Python2。*(我相信你正在使用它),所以它们可能是轻微的错误。