读取投票文本文件并打印结果而不打印正确数字的程序

时间:2017-11-08 20:24:28

标签: python text-files

这是我的代码,我需要它来阅读一行文字,这些文字仅由y组成,而n' sy意味着是n意味着没有意义弃权,我' m试图加起来是的票数。文本文件如下所示:

Aberdeenshire  
yyynnnnynynyannnynynanynaanyna  
Midlothian  
nnnnynyynyanyaanynyanynnnanyna  
Berwickshire  
nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny  

这是我的代码:

def main():
    file = open("votes.txt")
    lines = file.readlines()

    votes = 0
    count = 0
    count_all = 0
    for m in range(1,len(lines),2):
        line = lines[m]
        for v in line:
            if v == 'a':
                votes += 1
            elif v == 'y':
                count_all += 1
                count += 1
                votes += 1
            else:
                count_all += 1

        print("percentage:" + (str(count/count_all)))

    print("Overall there were ", (count/count_all),"  yes votes")

main()

2 个答案:

答案 0 :(得分:0)

首先,您应该注意到,file.readlines()实际上在每行末尾都显示\n,代码中的else将在>>> with open("votes.txt","r") as f: ... print(f.readlines()) ... ['Aberdeenshire\n', 'yyynnnnynynyannnynynanynaanyna\n', 'Midlothian\n', 'nnnnynyynyanyaanynyanynnnanyna\n', 'Berwickshire\n', 'nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny\n'] 块中处理,所以没有:

str

这也许可以解释为什么你找不到好的数字......

现在,为了使代码更有效率,我们可以查看\n的{​​{3}}方法,也可以使用{{1}删除那些split而不是readlines

with open("votes.txt","r") as f:
    full = f.read()
    lines = full.split("\n")
    votes = 0
    a = 0
    y = 0
    n = 0
    for m in range(1,len(lines),2):
        line = lines[m]
        votes += len(line) # I'm counting n's as well here
        a += line.count("a")
        y += line.count("y")
        n += line.count("n")
    print("Overall, there were " + str(100 * y / (y + n)) + "% yes votes.")

希望有所帮助!

答案 1 :(得分:0)

或多或少的pythonic one liner,它不会给你每个人/城市的投票:

from collections import Counter

l = """Aberdeenshire  
yyynnnnynynyannnynynanynaanyna  
Midlothian  
nnnnynyynyanyaanynyanynnnanyna  
Berwickshire  
nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny"""

Counter([char for line in l.split('\n')[1::2] for char in line.strip()])

返回:

Counter({'a': 11, 'n': 60, 'y': 22})