如何从大型文本文件中提取两个唯一单词之间的信息

18

我有大约150个文本文件,里面充满了角色信息。每个文件都包含两个唯一的单词(alpha和bravo),我想提取这些唯一单词之间的文本,并将其写入到另一个文件中。

手动操作时,我可以使用CTRL + F查找这两个单词并复制它们之间的文本,现在我想知道如何使用程序(最好是Python)来处理多个文件。

4个回答

35
你可以使用正则表达式来完成这个任务。
>>> st = "alpha here is my text bravo"
>>> import re
>>> re.findall(r'alpha(.*?)bravo',st)
[' here is my text ']

我的test.txt文件

alpha here is my line
yipee
bravo

现在使用open函数读取文件,然后应用正则表达式

>>> f = open('test.txt','r')
>>> data = f.read()
>>> x = re.findall(r'alpha(.*?)bravo',data,re.DOTALL)
>>> x
[' here is my line\nyipee\n']
>>> "".join(x).replace('\n',' ')
' here is my line yipee '
>>>

@JohnMachin:修复了 x 的问题。 - RanRag
sre_constants.error: nothing to repeat``` - DJ_Stuffy_K

12
a = 'alpha'
b = 'bravo'
text = 'from alpha all the way to bravo and beyond.'

text.split(a)[-1].split(b)[0]
# ' all the way to '

4
你可以通过添加1的计数来帮助分割,这样它就会停止寻找其他需要分割的实例:text.split(a,1) - PaulMcG

7

str.find 和它的兄弟函数 rfind 带有参数 startend

alpha = 'qawsed'
bravo = 'azsxdc'
startpos = text.find(alpha) + len(alpha)
endpos = text.find(bravo, startpos)
do_something_with(text[startpos:endpos]

如果所包含的文本很短且靠前,这是最快的方法。

如果所包含的文本相对较大,请使用:

startpos = text.find(alpha) + len(alpha)
endpos = text.rfind(bravo)

如果所包含的文本很短且靠近结尾,请使用:

endpos = text.rfind(bravo)
startpos = text.rfind(alpha, 0, endpos - len(alpha)) + len(alpha)

第一种方法无论如何都比从文本开头开始进行第二次搜索的天真方法好; 如果您的包含文本没有主导模式,请使用它。

2

不要使用正则表达式,而是使用Python的string.find方法。

>>>> unique_word_a = 'alpha'
>>>> unique_word_b = 'bravo'
>>>> s = 'blah blah alpha i am a good boy bravo blah blah'
>>>> your_string = s[s.find(unique_word_a)+len(unique_word_a):s.find(unique_word_b)].strip()
i am a good boy

2
如果我有多个唯一单词a和b的出现,我需要做哪些更改?如何创建一个索引来搜索唯一单词a和b的第5次出现之间的内容? - Amistad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接