删除列表中的字符

时间:2018-03-14 04:10:08

标签: python-3.x

我的任务是阅读一个文本文件并计算从1967年到1977年超级碗团队的胜利。到目前为止,我的程序只打印每一行的出现次数,并将其计为1,因为它们都有不同的年份。球队名称。我不知道如何从团队名称中删除多年。到目前为止我已经

def word_count():
    city_list = []
        city_file = open('win_count.txt', 'r')
        for city in city_file:
            city = city.rstrip('\n')
            city = city.split('\n')
            city_list.append(city)
        my_dict = {}
        city_file.close()
        for item in city_list:
            for city in item:
                if city in my_dict:
                    my_dict[city] += 1
                    else:
                        my_dict[city] = 1
        print('city\t\tCount')
        for key, value in my_dict.items():
            print(key,'\t', ':' , '\t', value)
word_count()

这是win_count.txt文件

1977 Oakland
1976 Pittsburgh
1975 Pittsburgh
1974 Miami
1973 Miami
1972 Dallas
1971 Baltimore
1970 Kansas City
1969 New York Jets
1968 Green Bay
1967 Green Bay

2 个答案:

答案 0 :(得分:0)

如果您对写入文件数据的格式有信心,可以用空格拆分城市,只需将city [1]附加到city_list。

问题出在这里。

for city in city_file:
   city = city.rstrip('\n')
   city = city.split('\n') # Splitting with '\n' will give ["1971 Baltimore", '']
   city_list.append(city) # This appends the list obtained from previous step into city_list.

在这里

my_dict = {}
city_file.close()
for item in city_list:
    for city in item:
        if city in my_dict: # Right way is to use my_dict.itervalues()

试试这个版本。

def word_count():
    city_list = []
    with open('win_count.txt', 'r') as city_file:
        temp_list = city_file.readlines()
        for item in temp_list:
            city = (item.rstrip('\n')).split(' ') #This gives you list of words like ['1971', 'Baltimore']
            city_list.append(city[1])
    my_dict = {}

    for item in city_list:
        if item in my_dict.itervalues():
            my_dict[item] += 1
        else:
            my_dict[item] = 1
    print('city\t\tCount')
    for key, value in my_dict.items():
        print("{:10}\t{}".format(key,value))

word_count()

答案 1 :(得分:0)

如果每行的乞讨只有4个字符加上一个空格,那么只需def word_count(): city_list = {} with open('win_count.txt', 'r') as city_file: for row in city_file: city_name = row[5:].rstrip('\n') if city_name in city_list: city_list[city_name] += 1 else: city_list[city_name] = 1 print('city\t\tCount') for key, value in city_list.items(): print(key,'\t', ':' , '\t', value) word_count()

即可获得城市名称
recyclerview