Python 如何在文本文件中查找给定单词的行号

Python 如何在文本文件中查找给定单词的行号

在本文中,我们将展示如何使用Python从文本文件中获取给定单词所在的行号。

假设我们已经取得了一个名为 TextFile.txt 的文本文件,其中包含一些随机文本。我们将返回给定单词所在的行号。

TextFile.txt

Good Morning TutorialsPoint
This is TutorialsPoint sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome TutorialsPoint
Learn with a joy

步骤

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储文本文件的路径。

  • 创建一个变量(保存行号)并将其初始值设置为1。

  • 输入单词作为静态/动态输入,并将其存储在变量中。

  • 使用 open() 函数(打开文件并返回文件对象作为结果)以只读模式打开文本文件,通过将文件名和模式作为参数传递给它(这里的“r”表示只读模式)。

with open(inputFile, 'r') as fileData:
  • 使用for循环遍历文本文件的每一行。

  • 使用 split() 函数(将字符串拆分成列表。我们可以定义分隔符;默认分隔符为任何空格),将文本文件的每一行拆分为一个单词列表并存储在一个变量中。

  • 使用if条件语句和 “in” 关键字,检查给定的单词是否在上述单词列表中。

in 关键字有两种使用方式−

The in keyword is used to determine whether a value exists in a sequence (list, range, string etc).

还可以在for循环中用来遍历一个序列

  • 如果给定的单词在对应的行中找到,则打印行号。

  • 增加行号的值1。

  • 使用 close() 函数关闭输入文件(用于关闭已打开的文件)。

示例

以下程序用于从文本文件中删除给定行并打印删除该行后的结果文件内容−

# input text file
inputFile = "ExampleTextFile.txt"

# storing the current line number
lineNumber = 1

# Enter the word 
givenWord = "TutorialsPoint"
print('The word {', givenWord, '} is present in the following lines:')

# Opening the given file in read-only mode. 
with open(inputFile, 'r') as fileData: 

   # Traverse in each line of the file
   for textline in fileData:

      # Splitting the line into list of words 
      wordsList = textline.split()

      # Checking if the given word is present in the above words list
      if givenWord in wordsList:

         # Print the line number, if the given word is found
         print(lineNumber)

         # Increase the value of linenumber by 1
         lineNumber += 1

# Closing the input file
fileData.close()

输出

执行时,上述程序将生成以下输出 –

The word { TutorialsPoint } is present in the following lines:
1
2
6

在这个程序中,我们读取一个包含一些随机文本的文本文件。我们创建了一个变量来存储当前行号,并将其初始化为1,即起始行号。我们逐行遍历文本文件,将每一行拆分成一个单词列表,并检查给定的单词是否在列表中。如果存在,则打印当前行号。对于每一行,行号的值增加1。

我们从这篇文章中学会了如何读取文件,逐行遍历文件,并从该行获取所有的单词。一旦获取到它们,我们可以反转单词,更改大小写,检查元音字母,检索单词长度等。我们还学会了如何计算行号以及如何在文件中搜索单词,这在一些常见的日常应用程序中得到广泛应用,例如在结果中查找名称,在某些代码中搜索关键字等。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程