📜  如何使用Python获取给定单词所在的行号?

📅  最后修改于: 2022-05-13 01:54:36.192000             🧑  作者: Mango

如何使用Python获取给定单词所在的行号?

要从存在给定单词的文件中获取行号,请创建一个列表,其中每个索引都包含每行的内容。为此,请按照以下说明进行操作。

首先,我们需要一个文件来读取。因此,使用下面的魔法函数在 Jupiter notebook 中创建一个文件:

%%writefile geeks.txt 
Hello, I am Romy 
I am a content writer at GfG 
Nice to meet you 
Hello, hii all fine

或者您可以使用任何.txt 文件。

Python3
# READ FILE
df = open("geeks.txt")
 
# read file
read = df.read()
 
# return cursor to
# the beginning
# of the file.
df.seek(0)
read


Python3
# create empty list
arr = []
 
# count number of
# lines in the file
line = 1
for word in read:
    if word == '\n':
        line += 1
print("Number of lines in file is: ", line)
 
for i in range(line):
    # readline() method,
    # reads one line at
    # a time
    arr.append(df.readline())


Python3
# Function that will return
# line in which word is present
def findline(word):
    for i in range(len(arr)):
        if word in arr[i]:
            print(i+1, end=", ")
 
 
findline("Hello")


输出:

'Hello, I am Romy\nI am a content writer at GfG\nNice to meet you\nHello, hii all fine' 
 

Python3

# create empty list
arr = []
 
# count number of
# lines in the file
line = 1
for word in read:
    if word == '\n':
        line += 1
print("Number of lines in file is: ", line)
 
for i in range(line):
    # readline() method,
    # reads one line at
    # a time
    arr.append(df.readline())

输出:

Number of lines in file is: 4
['Hello, I am Romy\n',
'I am a content writer at GfG\n', 
'Nice to meet you\n',
'Hello, hii all fine']

Python3

# Function that will return
# line in which word is present
def findline(word):
    for i in range(len(arr)):
        if word in arr[i]:
            print(i+1, end=", ")
 
 
findline("Hello")

输出:

1, 4
Hello is present in 1st and 4th line.