我正在尝试创建一个脚本,允许用户输入一些正则表达式,这些正则表达式将通过输入文件并检索匹配项。我目前正在使用ahocorasick,但在尝试输入正则表达式模式时遇到问题。
我在第二个raw_input(colour_regex)中输入一个正则表达式,但在下面收到此错误:
Traceback (most recent call last):
File "PLA_Enrichment_options.py", line 189, in <module>
main()
File "PLA_Enrichment_options.py", line 41, in main
tree.add(regex)
File "build/bdist.linux-x86_64/egg/ahocorasick/__init__.py", line 29, in add
TypeError: argument 1 must be string or read-only buffer, not _sre.SRE_Pattern
file_name = raw_input("What is the filename you wish to enhance? ")
enhanced_name = file_name.replace(".csv", "")
# User regexed input
tree = ahocorasick.KeywordTree()
print ("What regex would you like to use for colour? (Enter 'exit' to move on) ")
colour_regex = raw_input()
regex = re.compile(colour_regex)
while colour_regex != "exit":
tree.add(regex)
tree.make()
print 'Finding colour matches...'
output = open(enhanced_name + '-colour.csv', 'w')
file = open(feed_name, 'r')
for line in iter(file):
id, title, desc, link, image = line.strip('\n').split('\t')
offerString = '|'.join([title.lower(), desc.lower(), link.lower()])
keywords = set()
for match in tree.findall_long(offerString): # find colours
indices = list(match)
keyword = offerString[indices[0]:indices[1]]
if re.search(r'(?<![âêîôûäëïöüà èìòùáéÃóú])\b%s\b(?![âêîôûäëïöüà èìòùáéÃóú])' %(keyword), offerString):
keywords.add(keyword)
if keywords:
output.write('\t'.join([id, '|'.join(keywords), desc, link, image])+'\n')
else:
output.write('\t'.join([id, title, desc, link, image])+'\n')
file.close()
output.close()
任何正确方向的帮助/指导都会很棒。
由于
答案 0 :(得分:1)
tree = ahocorasick.KeywordTree()
regex = re.compile(colour_regex)
tree.add(regex)
您已将错误的类型传递给ahocorasick.KeywordTree.add()
regex
是一个已编译的正则表达式对象。类型为_sre.SRE_Pattern
。如果您改用原始字符串,则不会出现此错误。
tree.add(colour_regex)
此外,这将导致无限循环。我想你想要if
而不是while
,或者把colour_regex = raw_input()
放在循环中。
while colour_regex != "exit":