如何在特定单词所在的行中查找。[Python]

7

我正在尝试创建一个程序,用于计算行数、特定单词的数量,并告诉你它在哪一行。目前我已经实现了前两项,但是我不确定如何找到单词所在的行。有什么建议吗?这是我的当前代码:

 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 Chaudhary
我想打印整行,同时找到它所在的索引号。让我编辑我的问题。 - matrixCode
for index, line in enumerate(inF):... - Ashwini Chaudhary
1个回答

4
您的程序可以简化如下:
# read the file into a list of lines
with open('data.csv','r') as f:
    lines = f.read().split("\n")


print("Number of lines is {}".format(len(lines)))

word = 'someword' # dummy word. you take it from input

# iterate over lines, and print out line numbers which contain
# the word of interest.
for i,line in enumerate(lines):
    if word in line: # or word in line.split() to search for full words
        print("Word \"{}\" found in line {}".format(word, i+1))

以下是示例文本文件:

DATE,OPTION,SELL,BUY,DEAL
2015-01-01 11:00:01, blah1,0,1,open
2015-01-01 11:00:01, blah2,0,1,open
2015-01-01 11:00:01, blah3,0,1,open
2015-01-01 11:00:02, blah1,0,1,open
2015-01-01 11:00:02, blah2,0,1,someword
2015-01-01 11:00:02, blah3,0,1,open

该程序的结果为:
Number of lines is 7
Word "someword" found in line 6

请注意,这并不考虑一个例子,即您有子字符串的情况,例如,“dog”将被找到在“dogs”中。要获得完整的单词(即由空格分隔),您需要将行进一步拆分为单词。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接