[英]Find the lines in the text file
您將實現函數index(),該函數將文本文件的名稱和單詞列表作為輸入。 對於列表中的每個單詞,您的函數都將在文本文件中找到單詞所在的行,並打印相應的行號(編號從1開始)。 您應該只打開和讀取一次文件。
我只能計數一次。
def index(filename, words):
infile = open(filename)
content = infile.readlines()
infile.close()
count = {}
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
for word in count:
print('{:12}{},'.format(word, count[word]))
Output :index('raven.txt',['raven'])
raven 1,
Desired Output : index('raven.txt',['raven'])
raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 12(No of lines it appear)
可能會遇到相同的問題..我寫了下面..
def index(filename, lst):
infile = open(filename, 'r')
content = infile.readlines()
infile.close()
for word in lst:
print(word, end = '\t')
for line in range(len(content)):
if word in content[line]:
print(line+1, end= ' ')
print()
index('raven.txt', ['raven'])
未經測試,但應該可以工作
def index(filename, words):
with open(filename, "r") as f:
for i, line in enumerate(f):
for word in words:
if word in line:
return "%s at line %i" % (word, i + 1)
print index("some_filename", ["word1", "word2"])
或避免嵌套for循環:
def index(filename, words):
with open(filename, "r") as f:
for line, word in itertools.product(enumerate(f), words):
if word in line[1]:
return "%s at line %i" % (word, line[0] + 1)
print index("some_filename", ["word1", "word2"])
並使用列表推導:
def index(filename, words):
with open(filename, "r") as f:
return "\n".join("%s at line %i" % (word, line[0] + 1) for line, word in itertools.product(enumerate(f), words) if word in line[1])
print index("some_filename", ["word1", "word2"])
這個例子怎么樣:
File1.txt
Y
x
u
d
x
q
碼:
word='x'
i = 0
with open('file1.txt', 'r') as file:
for line in file:
i = i +1
if word in line:
print(i)
print('Found It')
在此示例中,您讀入一個文件,並逐行瀏覽。 在每一行中,您都查看一個單詞是否存在。 如果是這種情況,我們將在屏幕上打印一些內容。
編輯:
或定義為:
filename='file1.txt'
word='x'
def index(filename, word):
i = 0
with open(filename, 'r') as file:
for line in file:
i = i +1
if word in line:
print(i)
print('Found It')
index(filename, word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.