【问题标题】:Searching a text file and printing line numbers搜索文本文件并打印行号
【发布时间】:2014-07-08 02:02:25
【问题描述】:

如何让你的函数在文本文件中找到单词出现的行并打印相应的行号?

我必须打开一个包含该段落的文本文件,然后应该在该段落中搜索某些单词,然后打印这些单词的特定行号。

这是我目前所拥有的。

words = [network, devices, computer, fire, local, area, room, single]
    def index(string):
       lines = open('Network.txt', 'r')
       string = str(lines.read())
       lines.close()
       return string

【问题讨论】:

  • 没有任何代码搜索文件。
  • 我知道它会打开文件。这就是我问的原因!
  • 使用lines = lines.split('\n')lines 拆分为新行。这将返回一个列表,其中每一行作为一个元素。然后很容易找出哪一行有你要找的词。
  • @Ryan 最好使用for line in file 遍历文件,将文件视为可迭代的将自动拆分换行符(任何类型)。

标签: python file


【解决方案1】:

假设您已正确打开文件,这实际上非常简单。使用 file.read() 会拉入您不想要的整个文件。 If you are doing line-based processing, iterate through the file using with 因为它使文件的打开、关闭和错误处理变得更加容易:

with open(filename) as file:
    for line in file:
        #do something

您的逻辑的核心部分是enumerate(),它接受一个可迭代对象,并与每个迭代项一起返回一个计数。

words = ["word","another"]
for line_num,line in enumerate(file):
    if any([word in line for word in words]):
        print line_num, line

另一个因素是列表理解,它检查任何单词是否在一行上。 any() 函数“如果可迭代的任何元素为真,则返回真”。以及以下列表理解:

[word in line for word in words]

可以读作:

[告诉我如果word in line for 每个@ 987654334@ 所有的words].

如果 any 单词在该数组中,即您的单词中至少有一个是该行,那么它是真的,因此将被打印出来。

【讨论】:

  • 也许 1) any(word in line for word in words)words = {"word","another"}(即,在 any 中使用生成器与列表推导式,并使用集合而不是列表作为目标来测试单词。
  • 我使用的是 OP 为 words 提供的数据结构,并且考虑到我刚刚使用简单的列表理解进行了多么短,因为使用看起来像指令的函数可能是令人困惑。 any(stuff ...)any([stuff ...])
【解决方案2】:

如果您只想测试单个单词的存在,请使用相关行的enumerateset union

words={'some', 'target', 'words', 'in', 'a', 'set'}

with open(f_name) as fin:
    for line_num, line in enuemrate(fin):
        if set(line.split()) & words:
            print(line_num, line)

【讨论】:

    【解决方案3】:

    试试这个:

    words = []
    lines = {}
    for i in words:
        lines[i] = []
    
    with open("file", "r") as fin:
        curLine = 0
        for i in fin.readLines():
            for j in words:
                if j in i:
                    lines[j].append(curLine)
            curLine += 1
    
    for i in words:
        print lines[j]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2018-05-03
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多