2011-08-08 142 views
1

我有一段代码可以提取位于两个字符串之间的字符串。但是,此脚本只在一行上执行此操作。我想要在完整文件上执行此操作并获取所有在这两个词之间的词汇。Python中的文件操作

注:这两个词fixed.For例如:如果我的代码是一样的东西

'const int variablename=1' 

然后我想的'int''='之间躺在文件中的所有单词的列表。 这是当前脚本:

s='const int variablename = 1' 

k=s[s.find('int')+4:s.find('=')] 

print k 
+0

“int”和“=”之间允许的是什么? –

回答

2
with open(filename) as fn: 
    for row in fn: 
     # do something with the row? 
3

如果文件舒适,适合到内存中,你可以用一个正则表达式调用得到这样的:

import re 
regex = re.compile(
r"""(?x) 
(?<= # Assert that the text before the current location is: 
\b  # word boundary 
int # "int" 
\s  # whitespace 
)  # End of lookbehind 
[^=]* # Match any number of characters except = 
(?<!\s) # Assert that the previous character isn't whitespace. 
(?=  # Assert that the following text is: 
\s* # optional whitespace 
=  # "=" 
)  # end of lookahead""") 
with open(filename) as fn: 
    text = fn.read() 
    matches = regex.findall(text) 

如果二者之间可以只有一个字int=,那么正则表达式更简单一点:

regex = re.compile(
r"""(?x) 
(?<= # Assert that the text before the current location is: 
\b  # word boundary 
int # "int" 
\s  # whitespace 
)  # End of lookbehind 
[^=\s]* # Match any number of characters except = or space 
(?=  # Assert that the following text is: 
\s* # optional whitespace 
=  # "=" 
)  # end of lookahead""") 
+0

'[^ =] *#匹配任意数量的字符,除了='也会匹配空格。它应该是'[^ =] *'(或'\ s')。 – jsz

+0

不知道这是个好主意 - 谁知道空间是否也可以成为预期匹配的一部分? –

+0

那么,这只是与以下'(?=)'不一致。你在'[^]'中有什么应该匹配下面的loodahead'(?=)'。如果预期的匹配可能包含空格,为什么还要在前瞻中包含'\ s'? – jsz

0

如果你想要一个快速和肮脏的方法,你在一个类Unix系统。

我只是应该在文件上使用grep。 然后,我将分割字符串以识别模式和我想要的数据。

1

我会在整个文本上使用正则表达式(你也可以在一行上完成)。这会在“int”和“=”之间打印字符串

import re 

text = open('example.txt').read() 
print re.findall('(?<=int\s).*?(?=\=)', text) 
+0

感谢您的工作。这服务我的目的:) – neon