【问题标题】:Iterating through a .txt file in an odd way以一种奇怪的方式遍历 .txt 文件
【发布时间】: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


    【解决方案1】:

    我想你的意思是:

    import collections
    
    counts = collections.defaultdict(int)
    
    word = 'epic'
    
    counts[word] += 1
    

    显然,word 可以做的比我多,但你没有向我们展示任何代码,所以...

    编辑

    好的,看看你的代码,我建议你明确区分评级和文本。拿这个:

    def make_list(file):
        lst = []
        for line in file:
            lst2 = line.split(' ')
            del lst2[-1]
            lst.append(lst2)
        return lst
    

    并将其转换为:

    def parse_ratings(file):
        """
        Given a file of lines, each with a numeric rating at the start,
        parse the lines into score/text tuples, one per line. Return the
        list of parsed tuples.
        """
        ratings = []
        for line in file:
            text = line.strip().split()
            if text:
                score = text[0]
                ratings.append((score,text[1:]))
        return ratings
    

    然后你可以一起计算这两个值:

    def match_reviews(word, ratings):
        cnt = 0
        scores = []
    
        for score,text in ratings:
            n = text.count(word)
            if n:
                cnt += n
                scores.append(score)
    
        return (cnt, scores)
    

    【讨论】:

    • 我已经弄清楚了计数部分。我需要能够遍历 .txt 文件,并且每当程序要查找的单词出现时,它应该将该单词前面的整数附加到列表中。
    • 好的,我添加了一些可能有帮助的代码。我认为您需要开始更正式地处理您的数据。将乐谱与文字分开,然后将它们放在官方位置。您将永远知道什么是什么。
    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 2017-12-04
    • 1970-01-01
    • 2019-08-03
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多