[英]how do i get this program to write each line with a given word to a file?
[英]For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file
對於任何用戶指定的文本文件,程序將使用輸出文件中找到單詞的行號讀取,分析和寫入每個單詞。 一個單詞可能出現在多行中。 一個單詞在一行中不止一次顯示,行號僅記錄一次。 要求用戶輸入文本文件的名稱。 使用try / except進行無效的用戶輸入。 然后程序讀取文本文件的內容並創建一個字典,其中鍵值對描述如下:
一旦構建了字典,程序就應該創建另一個名為“word_index.txt”的文本文件。 接下來,將字典的內容寫入文件,作為在字典中存儲為鍵的單詞的字母列表(對鍵進行排序),以及單詞出現在原始文件中的行號。
看下面的代碼
import string
fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
L_N=0
for line in fhand:
line= line.rstrip()
line = line.translate(line.maketrans(' ', ' ',string.punctuation))
line = line.lower()
words = line.split()
L_N+=1
for word in words:
if word not in counts:
counts[word]= [L_N]
else:
if L_N not in counts[word]:
counts[word].append(L_N)
for h in range(len(counts)):
print(counts)
out_file = open('word_index.txt', 'w')
out_file.write('Text file being analyzed is: '+str(fname)+ '\n\n')
out_file.close()
結果應該打印一次結果,但我遇到的問題是它一次打印多次。
由於你在for循環中打印你的字典,它將被打印n次 - n是字典的長度 - 所以你只需刪除這個循環:
for h in range(len(counts)):
print(counts)
而是添加它:在這里我們只需循環遍歷字典即可獲得每對
for key, value in counts.items():
print('key: ', key, 'value: ', value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.