[英]count how many times the same word occurs in a txt file
您好,我正在為此苦苦掙扎:我有一個 txt 文件,打開后如下所示:
Jim, task1\n
Marc, task3\n
Tom, task4\n
Jim, task2\n
Jim, task6\n
我想檢查有多少重復名稱。 我只對第一個字段(即人名)感興趣。
我試圖在這個網站上尋找答案,但我找不到任何有用的東西,因為在我的情況下我不知道哪個名稱是重復的,因為這個文件 txt 會經常更新。
由於我是 Python/編程的新手,有沒有一種簡單的方法可以解決這個問題而不使用任何字典或列表理解或不導入模塊?
謝謝
same_word_count = 0
with open('tasks.txt','r') as file2:
content = file2.readlines()
for line in content:
split_data = line.split(', ')
user = split_data[0]
word = user
if word == user:
same_word_count -= 1
print(same_word_count)
您可以執行以下操作。
word = "Word" # word you want to count
count = 0
with open("temp.txt", 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
count=count+1
print("Occurrences of the word", word, ":", count)
或者你可以獲得所有單詞出現的列表
# Open the file in read mode
text = open("sample.txt", "r")
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.