【问题标题】:Finding string in text file, and then printing several characters beyond that in Python在文本文件中查找字符串,然后在 Python 中打印多个字符
【发布时间】:2012-08-10 02:09:39
【问题描述】:

使用 Python,我需要在文本文件中搜索字符串“that/”

然后我需要获取行号(目前通过使用枚举来实现),然后打印出来 "that\" + 直到下一个空格的剩余文本。

示例文本:First/LS thing/NN I/PRP want/VBP to/TO ask/VB is/VBZ if/IN you/PRP remember/VBP any/DT books/NNS that/IN you/PRP read/ VBP as/IN a/DT child/NN

示例输出:that/IN 14

这是我现在拥有的代码,它可以正常运行,但无论在哪里打印“that/xx”,它什么都不会打印。

with open(filename) as f:
            for num, line in enumerate(f, 1):
                if 'that/' in line:
                    myString = line
                    mySub = myString[myString.find('that/'):myString.find(' ')]
                    print(mySub, str(num))
                    formattedLines.append(mySub + ' ' + str(num) + '\n')

【问题讨论】:

  • 又是哪个thatthat 带有正向 /that 带有反斜杠?
  • 你的文件是用每一行的每个字符串格式化的吗?
  • 你的问题是 find(' ') 可能发生在 find('that/') 之前,所以在搜索 'that/' 之后尝试搜索 ' '(只需添加 find 返回的索引) find 也会返回 -1 以防万一它什么也没找到,这将是您代码的另一个缺点

标签: python search line substring nltk


【解决方案1】:

我认为问题在于空格可能发生在that/ 之前。在找到that/ 的索引处开始搜索空格:

with open(filename) as f:
    for num, line in enumerate(f, 1):
        if 'that/' in line:
            myString = line
            where_is_that = myString.find('that/')
            mySub = myString[where_is_that:myString.find(' ', where_is_that)]
            print(mySub, str(num))
            formattedLines.append(mySub + ' ' + str(num) + '\n')

【讨论】:

  • 谢谢,工作完美:)。不敢相信我没想到!我对 Python 很陌生。
【解决方案2】:

我认为myString.find(' ') 是问题所在。这可以在 'that/' 之前找到一个字符串,因此您可以尝试获取 myString[50:3]

试试这个:

with open(filename) as f:
    for num, line in enumerate(f, 1):
        if 'that/' in line:
            start = myString.find('that/')
            offset = myString[start:].find(' ')
            end = start + offset if offset != -1 else len(myString)
            mySub = myString[start:end]
            print(mySub, str(num))
            formattedLines.append(mySub + ' ' + str(num) + '\n')

【讨论】:

  • 但是,@KyleParker 将可选参数传递给find,它指示查找函数必须从哪个位置开始。
  • 我在问题代码中没有看到可选参数。你能指出来吗?
  • 抱歉,@BrendenBrown,我正在查看并尝试其中一个回复中的代码
  • 你不应该删除你的答案,stummjr,检查 -1 是一个有用的补充。我会把它添加到我的答案中。
【解决方案3】:

我决定采用不同的方法,并使用正则表达式:

import re

def analyze(line, word):
    regex = r'\b{0}/[^\W]*'.format(word)
    match = re.search(regex, line)
    return match.group() if match else None

def extract(filename, word):
    output = []
    with open(filename) as f:
        for num, line in enumerate(f, 1):
        result = analyze(line, word)
        if result:
            output.append(result + ' ' + str(num) + '\n')
    return output

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2013-05-15
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多