我有大约150个文本文件,里面充满了角色信息。每个文件都包含两个唯一的单词(alpha和bravo),我想提取这些唯一单词之间的文本,并将其写入到另一个文件中。
手动操作时,我可以使用CTRL + F查找这两个单词并复制它们之间的文本,现在我想知道如何使用程序(最好是Python)来处理多个文件。
我有大约150个文本文件,里面充满了角色信息。每个文件都包含两个唯一的单词(alpha和bravo),我想提取这些唯一单词之间的文本,并将其写入到另一个文件中。
手动操作时,我可以使用CTRL + F查找这两个单词并复制它们之间的文本,现在我想知道如何使用程序(最好是Python)来处理多个文件。
>>> 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 '
>>>
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 '
text.split(a,1)
。 - PaulMcGstr.find
和它的兄弟函数 rfind
带有参数 start
和 end
。
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)
不要使用正则表达式,而是使用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
x
的问题。 - RanRagsre_constants.error: nothing to repeat```
- DJ_Stuffy_K