我正在尝试创建一个程序,用于计算行数、特定单词的数量,并告诉你它在哪一行。目前我已经实现了前两项,但是我不确定如何找到单词所在的行。有什么建议吗?这是我的当前代码:
name = input('Enter name of the text file: ')+'.txt'
file = open(name,'r')
myDict = {}
linenum = 0
for line in file:
line = line.strip()
line = line.lower()
line = line.split()
linenum += 1
print(linenum-1)
count = 0
word = input('enter the word you want us to count, and will tell you on which line')
#find occurence of a word
with open(name, 'r') as inF:
for line in inF:
if word in line:
count += 1
#find on which line it is
P.S:我希望找到行的索引号,而不是打印整行内容。
if word in line:
条件为True
时,只需执行print line,
。如果您想匹配确切的单词而不仅仅是子字符串,请使用带有单词边界的正则表达式。 - Ashwini Chaudharyfor index, line in enumerate(inF):...
- Ashwini Chaudhary