gpt4 book ai didi

python - 重命名列表中的国家

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:14 25 4
gpt4 key购买 nike

我有一个这样格式化的文本文件,每行的电影名称、评分和原产国均由制表符分隔:

"3:0 f¸r die B‰rte" (1971)  6.8 West Germany
"3K Check In" (2002) 4.3 Federal Republic of Yugoslavia
"3MW: Rivers of Blood" (2008) 7.9 UK
"3Way" (2008) 8.2 USA
"3rd Rock from the Sun" (1996) 7.8 USA
"3rd and Bird" (2008) 7.8 UK
"3satfestival" (2000) 6.7 Germany

我的目标是计算每个国家/地区的平均评分,这与我下面的代码一起使用。但是,我也想将一些国家重命名,例如将“西德”重命名为“德国”,以便可以将它们的评分加在一起,但我的代码不起作用,即。 “西德”和“德国”的评分仍然分开计算。我可以做出哪些改变?

import collections

MovieRating = collections.namedtuple('MovieRating', ['countryorigin', 'ratingscore'])

ratings = {}

movie = open("movieRatingscore.txt", "r") #open the country rating data file

for line in movie.readlines():
line.rstrip()
(moviename, ratingscore, countryorigin) = line.split('\t')
if countryorigin == 'West Germany':
countryorigin = 'Germany'
ratingscore = float(ratingscore)
if countryorigin in ratings:
ratings[countryorigin].append(ratingscore)
else:
ratings[countryorigin] = [ratingscore]

average = lambda alist: sum(alist)/len(alist)
average_ratings = [MovieRating(countryorigin, average(ratings[countryorigin])) for countryorigin in ratings]

print "\nCountries with the highest average movie rating\n------------------------------"
sorted_ratings = sorted(average_ratings, key=lambda countryorigin: countryorigin.ratingscore, reverse=True)
for i, j in enumerate(sorted_ratings):
print '%i. %s \t%g' % (i + 1, j.countryorigin, j.ratingscore)

最佳答案

最简单的方法就是用字典来代替单词。检查示例代码:

dt = {'West Germany': 'Germany', 'another': 'Replaced'}
for line in movie.readlines():
for item in dt:
line = line.replace(item, dt[item])

关于python - 重命名列表中的国家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25081320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com