[英]How to find the frequency of words in a list created from a .csv file
我正在嘗試編寫一個程序,該程序首先讀取輸入文件的名稱,然后使用 csv.reader() 方法讀取文件。 該文件包含以逗號分隔的單詞列表。 程序應該輸出單詞及其頻率(每個單詞在文件中出現的次數),沒有任何重復。
文件input1.csv有hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy
到目前為止,我有這個:
import csv
with open('input1.csv', 'r') as wordsfile:
words_reader = csv.reader(wordsfile)
for row in words_reader:
for word in row:
count = row.count(word)
print(word, count)
但我的輸出是這樣的:“你好 1 貓 2 男人 2 嘿 2 狗 2 男孩 2 你好 1 男人 2 貓 2 女人 1 狗 2 貓 1 嘿 2 男孩 2”
我正在嘗試輸出這個但沒有任何重復,我很困惑,任何幫助將不勝感激。
import csv
input1 = input()
with open(input1, 'r') as wordsfile:
words_reader = csv.reader(wordsfile)
for row in words_reader:
list_of_words = row
no_duplicates_in_list = list(dict.fromkeys(list_of_words))
listlength = len(no_duplicates_in_list)
for i in range(listlength):
print(no_duplicates_in_list[i], list_of_words.count(no_duplicates_in_list[i]))
與 Aryman 的幾乎相同,但順序與 csv 中的相同
嘗試使用 set()
import csv
with open('input1.csv', 'r') as wordsfile:
words_reader = csv.reader(wordsfile)
for row in words_reader:
list_of_words = set(row)
for word in list_of_words:
count = row.count(word)
print(word, count)
我對 csv 庫不是很熟悉,我不知道 row 是否是一個列表,或者如果這會引發錯誤,我不會很抱歉。 如果 row 是一個字符串,您可能可以使用
row = row.split()
list_of_words = set(row)
希望能幫助到你。
好的,所以我對 Python 非常了解,但我能夠在大約一個小時內嘗試不同的 for 循環等后弄清楚這一點。我最終堅持使用列表,因為這是說明中指定的任務。 為了擺脫第一個列表中的重復項,我創建了第二個列表並嵌套了一個 if 語句,該語句只添加不包含在其中的單詞,從而生成一個新列表,其中包含第一個單詞的每個單詞的一個副本。
filename = input()
words = []
new_words = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for row in reader:
for word in row:
words.append(word)
for word in words:
freq = words.count(word)
if word not in new_words:
new_words.append(word)
print(word, freq)
import csv
name = input()
with open(name, 'r') as myfile:
Reader = csv.reader(myfile, delimiter=',')
dictionary = dict()
for l in Reader:
for m in l:
if m in dictionary:
dictionary[m] = dictionary[m] + 1
else:
dictionary[m] = 1
for n in list(dictionary.keys()):
print("{} {}".format(n, dictionary[n]))
導入 csv words = {} user_file = input() with open(user_file, "r") as csvfile: inputreader = csv.reader(csvfile) for row in inputreader: listofwords = row
for i in row:
if i in words:
words[i] += 1
else:
words[i] = 1
for i in words: print(i, words[i])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.