Beginner here. I'm currently writing a program that will turn every word in a "movie reviews" text file into a key, storing a list value containing the review number and the number of times the word has been seen. For example:
4 I loved it
1 I hated it
... might look like this as a dictionary:
words['i'] = [5,2]
words['loved'] = [4,1]
words['it'] = [5,2]
words['hated'] = [1,1]
However, this is the output I've been getting:
{'i': [1, 2], 'loved': [4, 1], 'it': [1, 2], 'hated': [1, 1]}
I figured out the counter part, but I can't figure out how to update the review number. Here is my code so far:
def main():
reviews = open("testing.txt", "r")
data = reviews.read();
reviews.close()
# create new dictionary
words = {}
# iterate over every review in text file
splitlines = data.split("\n")
for line in splitlines:
lower = line.lower()
value = lower.split()
rev = int(value[0])
for word in value:
if word.isalpha():
count = 1
if word not in words:
words[word] = [rev, count]
else:
words[word] = [rev, count + 1]
How can I update the review number count?
This is pretty easy to do. Assuming each key has only 2 items in the value list:
if word not in words:
words[word] = [rev, 1]
else:
temp = words[word][1]
words[word] = [rev, temp + 1]
When updating the count, you're using count + 1
, but count
will always be 1 here; you need to retrieve the existing count first, using something like: count = words[word][1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.