Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何存储正则表达式中关键术语的列表(或dict)-python_Python_Regex_Dictionary - Fatal编程技术网

如何存储正则表达式中关键术语的列表(或dict)-python

如何存储正则表达式中关键术语的列表(或dict)-python,python,regex,dictionary,Python,Regex,Dictionary,我对python和regex很陌生,所以请耐心听我说。 我试图读入一个文件,在忽略大小写的情况下使用正则表达式匹配一个特定的名称,并在每次找到它时进行存储。例如,如果文件由Bill组成,我需要将每个变体存储在字典或列表中。 当前代码: import re import sys import fileinput if __name__ == '__main__': print "flag" pattern = re.compile("""([b][i][l][l])""")

我对python和regex很陌生,所以请耐心听我说。 我试图读入一个文件,在忽略大小写的情况下使用正则表达式匹配一个特定的名称,并在每次找到它时进行存储。例如,如果文件由
Bill
组成,我需要将每个变体存储在字典或列表中。 当前代码:

import re
import sys
import fileinput
if __name__ == '__main__':
    print "flag"
    pattern = re.compile("""([b][i][l][l])""")
    for line in fileinput.input():
        variation=set(pattern.search(line, re.I))

    print variation.groupdict()
    print "flag2"
当运行时,代码将返回一个错误:“NoneType”不能被迭代(或者沿着这些行)。 那么如何存储每个变体呢

提前谢谢

我想这是你想要的。这当然也可以在编译的正则表达式上获得。但是,您得到的特定错误代码似乎表明您是。试一试

我会用芬德尔:

re.findall(r'bill', open(filename).read(), re.I)
非常简单:

>>> s = 'fooBiLL bill BILL bIlL foo bar'
>>> import re
>>> re.findall(r'bill', s, re.I)
['BiLL', 'bill', 'BILL', 'bIlL']

为什么是方括号
[b]
相当于
b
,因为方括号表示字符类(即
[abc]
=“a、b或c中的任何一个”)。
([b][i][l][l])
多么奇怪的正则表达式啊。我想这不是你想做的。我一直在使用
[b][I][l][l]
,直到我开始做一些事情。所以我应该使用
variation=set(pattern.findall(line,re.I))
我在使用这个集合,所以没有重复。
>>> s = 'fooBiLL bill BILL bIlL foo bar'
>>> import re
>>> re.findall(r'bill', s, re.I)
['BiLL', 'bill', 'BILL', 'bIlL']