这个单词在一个文本文件中出现了几行



我正试图找到单词"爱丽丝";出现在我创建的alice.txt文件的内部。我还在用一本词典来记单词"的次数;爱丽丝";出现在文本文件内部,并且该行编号为单词";爱丽丝";出现在文本文件的内部;爱丽丝";位于我的文本文件内部。现在我正在计算这个单词在我的文本文件中出现了多少行。我去掉了单词,我已经把单词分开了,但我不知道之后该怎么办。我试着输入if for word in line将行号增加1,但它只打印第1行和第2行。

这是我的代码:

import re
file = open('alice.txt', 'r')
word_dictionary = {
'rabbit' : {'count' : 51, 
'lines' : [ 1, 2, 3, 9, 26, 31, 63, 65, 66, 70, 72, 73, 74, 79, 80, 81, 192, 200, 201],
'chapters' : ['I','IV',] 
},
'Alice' : {'count' : 52,
'lines' : [ 5, 8, 17, 23, 29, 49, 57, 83, 93, 96, 104, 109, 117, 123, 126, 133, 137, 149, 161, 169, 175, 183, 190, 197, 204, 224, 232, 240, 249, 253, 264, 270, 306, 314, 327, 338, 346, 357, 368, 370, 374, 381, 384, 388, 397, 399, 405, 413, 419, 435, 438, 445],
'chapters' : ['I', 'II']

}
}

text = file.readlines()
chapter_number = ''
line_number = 0
word = input("Enter the word to search for: ")
#reads each line
for line in text:
line = line.strip()
line = line.split()
if word in line: 
line_number += 1
print(line_number)
def count_of_words():
print('The word count for ',word, 'is', word_dictionary[word]['count'])
def count_of_lines():
print('The lines that this word occurs is', word_dictionary[word]['lines'])
def count_of_chapters():
print('The chapters that this word occurs in is', word_dictionary[word] 
['lines'])

您可以这样做(我使用字符串而不是文件(。

entry={'count' : 0,
'lines' : [ ],
'chapters' : []}
word_dictionary = {}
#file = open('alice.txt', 'r')
#text = file.readlines()
text='Rabbit, hole, Alice, nAlice '.split('n')
chapter_number = ''
line_number = 0
word = 'Alice'
word_dictionary[word]=entry
print(word_dictionary)
#reads each line
for line in text:
line = line.strip()
words= line.split()
for text_word in words:
if text_word==word:
word_dictionary[word]['count']+=1
line_number += 1
print(line_number)
print(word_dictionary)

编辑:搜索整个单词,但不处理以标点符号结尾的单词,也不处理大写与小写。

最新更新