我正在尝试创建一个程序,它计算行数,计算一个特定单词,然后告诉你它在哪一行.现在我做了前两个,但我不知道如何找到这个词的哪一行.有什么建议 ?这是我目前的代码:
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
Run Code Online (Sandbox Code Playgroud)
PS:我想罚款线的索引号,而不是打印整行
您的程序可以简化如下:
# 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))
Run Code Online (Sandbox Code Playgroud)
对于以下示例文本文件:
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
Run Code Online (Sandbox Code Playgroud)
该计划的结果是:
Number of lines is 7
Word "someword" found in line 6
Run Code Online (Sandbox Code Playgroud)
请注意,这不考虑您有子串的示例,例如"狗"将在"狗"中找到.要拥有完整的单词(即用空格分隔),您需要另外将行拆分为单词.