在文本文件中查找字符串,然后在Python中打印多个字符

时间:2012-08-13 19:46:12

标签: python search line substring nltk

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

然后我需要获取行号(目前通过使用枚举来执行此操作),然后打印出来 “那个\”+剩下的文字直到下一个空格。

示例文本:第一个/ LS事件/ NN I / PRP想要/ VBP到/要求/ VB是/ VBZ如果/ IN你/ PRP记住/ VBP任何/ DT书籍/ NNS那个/ IN你/ PRP读/ VBP as / IN a / DT child / NN

示例输出:/ 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')

3 个答案:

答案 0 :(得分:1)

我认为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')

答案 1 :(得分: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')

答案 2 :(得分:1)

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

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