【发布时间】:2016-08-18 05:49:21
【问题描述】:
我要做的是编写一个程序,该程序打开一个包含电影评论的 .txt 文件,其中评级是 0-4 之间的数字,然后是电影的简短评论。然后,程序会提示用户打开第二个文本文件,其中包含将与评论匹配的单词,并根据评论给出一个数值。
例如,通过这两个示例审查它们在 .txt 文件中的显示方式:
4 一部近乎史诗般的喜剧,源于经历中年危机的主角的真诚表演。 2 马苏德的故事是一部史诗,也是一部悲剧,记录了一位顽强、人道的斗士,他也是历史的囚犯-LRB-,最终成为受害者-RRB-。
所以,如果我正在寻找“epic”这个词,它会将该词的计数增加 2(我已经知道),因为它出现了两次,然后将值 4 和 2 附加到一个列表中该词的评分。
如何将这些整数附加到与该单词相关的列表或字典中?请记住,我需要为单词列表中的每个单词创建一个新列表或字典键。
请,谢谢。很抱歉,如果这措辞不好,编程不是我的强项。
我所有的代码:
def menu_validate(prompt, min_val, max_val):
""" produces a prompt, gets input, validates the input and returns a value. """
while True:
try:
menu = int(input(prompt))
if menu >= min_val and menu <= max_val:
return menu
break
elif menu.lower == "quit" or menu.lower == "q":
quit()
print("You must enter a number value from {} to {}.".format(min_val, max_val))
except ValueError:
print("You must enter a number value from {} to {}.".format(min_val, max_val))
def open_file(prompt):
""" opens a file """
while True:
try:
file_name = str(input(prompt))
if ".txt" in file_name:
input_file = open(file_name, 'r')
return input_file
else:
input_file = open(file_name+".txt", 'r')
return input_file
except FileNotFoundError:
print("You must enter a valid file name. Make sure the file you would like to open is in this programs root folder.")
def make_list(file):
lst = []
for line in file:
lst2 = line.split(' ')
del lst2[-1]
lst.append(lst2)
return lst
def rating_list(lst):
'''iterates through a list of lists and appends the first value in each list to a second list'''
rating_list = []
for list in lst:
rating_list.append(list[0])
return rating_list
def word_cnt(lst, word : str):
cnt = 0
for list in lst:
for word in list:
cnt += 1
return cnt
def words_list(file):
lst = []
for word in file:
lst.append(word)
return lst
##def sort(words, occurrences, avg_scores, std_dev):
## '''sorts and prints the output'''
## menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n Sort Options\n 1. Sort by Avg Ascending\n 2. Sort by Avg Descending\n 3. Sort by Std Deviation Ascending\n 4. Sort by Std Deviation Descending", 1, 4)
## print ("{}{}{}{}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))
## if menu == 1:
## for i in range (len(word_list)):
## print ("{}{}{}{}".format(cnt_list.sorted[i],)
def make_odict(lst1, lst2):
'''makes an ordered dictionary of keys/values from 2 lists of equal length'''
dic = OrderedDict()
for i in range (len(word_list)):
dic[lst2[i]] = lst2[i]
return dic
cnt_list = []
while True:
menu = menu_validate("1. Get sentiment for all words in a file? \nQ. Quit \n", 1, 1)
if menu == True:
ratings_file = open("sample.txt")
ratings_list = make_list(ratings_file)
word_file = open_file("Enter the name of the file with words to score \n")
word_list = words_list(word_file)
for word in word_list:
cnt = word_cnt(ratings_list, word)
cnt_list.append(word_cnt(ratings_list, word))
对不起,我知道它很乱而且很不完整。
【问题讨论】:
标签: list python-3.x dictionary iteration