如何找到特定单词的哪一行。 [蟒蛇]

时间:2015-02-20 02:57:33

标签: python

我正在尝试创建一个程序,对行进行计数,计算特定单词,然后告诉您它在哪一行。现在我做了前两个,但我不知道如何找到这个词在哪一行。有什么建议 ?这是我目前的代码:

 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:我想要细化该行的索引号,而不是打印整行

1 个答案:

答案 0 :(得分: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

请注意,这并未考虑您有子串的示例,例如: "狗"将在"狗"中找到。要有完整的单词(即用空格分隔),你需要另外将行分成单词。