2011-08-08 32 views
1

私は2つの文字列の間にある文字列を抽出するコードを持っています。しかし、このスクリプトはこの行だけを実行します。完全なファイルに対してこの操作を実行したいそれらの2つの単語の間にあるすべての単語。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

これはちょうど次の '(?=)'と矛盾しています。あなたが '[^]'で持っているものは、以下のようなものです( '=?')。目的のマッチにスペースが含まれている場合は、先読みに '\ s'を含めて気にしないのはなぜですか? – jsz

0

あなたが素早く汚れた方法を望んでいれば、あなたはUNIX系のシステムにいます。

ファイルにはgrepを使用してください。 それから私はパターンと私が欲しいデータを認識するために文字列を分割します。

1

私は全文に正規表現を使用します(あなたは1行でもそれを行うことができます)。これは、 "int"と "="の間に許される文字列を出力します。

import re 

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

私の目的を果たす仕事のおかげで:) – neon

関連する問題