0

我正在尝试从用户那里获取输入并想要编译由每个字符组成的正则表达式,我尝试使用 list 并使用 list 作为失败的参数。

我不想匹配完整的字符串,但只匹配单个字符更具体

   x = raw_input("Enter string of length 7 to generate your scrabble helper: ")
    a = []
    for i in x:
        a.append(i)
    print(a)
    p = re.compile(a)

但这失败了!!!!

Traceback (most recent call last):
  File "scrabb.py", line 8, in <module>
    p = re.compile(a)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 232, in _compile
    p = _cache.get(cachekey)
TypeError: unhashable type: 'list'
4

3 回答 3

2

a是一个列表,re.compile()需要一个字符串。变量名i通常只用于整数,例如ch用于字符(如果你要使用短变量名,你应该遵守约定:-)

也许是这样的:

usertext = raw_input("Enter string of length 7 to generate your scrabble helper: ")
lst = []
for ch in usertext:
    lst.append(ch)
print(lst)
scrabble_re = re.compile(''.join(lst))

或者只是等价的,但要短得多:

usertext = raw_input("Enter string of length 7 to generate your scrabble helper: ")
scrabble_re = re.compile(usertext)

?

于 2012-08-11T10:30:40.427 回答
2

我不确定我是否完全了解您的需求,但也许这样的事情会有所帮助:

x = raw_input("Enter string of length 7 to generate your scrabble helper: ")
p = re.compile('|'.join((c for c in x)))

这应该匹配输入字符串中的每个字符,而不是整个字符串。您应该确保用户输入中没有特殊字符,但这是另一个问题。

于 2012-08-11T10:31:55.363 回答
1

听起来您对查找两个字符串之间的字符重叠更感兴趣:

x = raw_input('enter string')
y = 'aeiou'

overlap = list(set(x) & set(y))

print(overlap)

x这将打印在和之间共享的字符y。我不完全理解您要做什么,但是正则表达式是高级编程中被滥用最多的东西,只有在您真正需要它们时才应该使用它们。

于 2012-08-11T10:37:59.233 回答