[英]Python regular expression to parse a list into text for a response
When I run the code below I get: 当我运行下面的代码时,我得到:
Thank you for joining, ['cars', 'gas', 'jewelry']but['bus', 'join'] are not keywords.
How can I effectively turn the lists in to just strings to be printed? 如何有效地将列表变成仅要打印的字符串? I suspect I may need a regular expression... this time :)
我怀疑这次可能需要一个正则表达式...)
import re
pattern = re.compile('[a-z]+', re.IGNORECASE)
text = "join cars jewelry gas bus"
keywordset = set(('cars', 'jewelry', 'gas', 'food', 'van', 'party', 'shoes'))
words = pattern.findall(text.lower())
notkeywords = list(set(words) - keywordset)
keywords = list(keywordset & set(words))
if notkeywords == ['join']:
print "Thank you for joining keywords " + str(keywords) + "!"
else:
print "Thank you for joining, " + str(keywords) + "but" + str(notkeywords) + " are not keywords."
To convert list to strings use str.join like this 要将列表转换为字符串,请使用str.join这样
print "Thank you for joining keywords " + ",".join(keywords) + "!"
This if notkeywords == ['join']:
is not a way to compare list elements. if notkeywords == ['join']:
这不是比较列表元素的方法。
>>> mylist = [1,2]
>>> mylist == 1
False
you should in
operator to check for equality. 您应该
in
运算符中检查是否相等。
>>> mylist = [1,2]
>>> 1 in mylist
True
Just use someString.join(list)
: 只需使用
someString.join(list)
:
if notkeywords == ['join']:
print "Thank you for joining keywords " + ", ".join(keywords) + "!"
else:
print "Thank you for joining, " + ", ".join(keywords) + "but" + ", ".join(notkeywords) + " are not keywords."
If I understood your question correctly, you'll want to use the .join() string method to combine the list before printing it. 如果我正确理解了您的问题,则需要在打印列表之前使用.join()字符串方法组合列表。
For example: 例如:
', '.join(my_list) ','。join(my_list)
will give you comma separated output. 将为您提供逗号分隔的输出。 ', ' can be whatever kind of separator you like.
','可以是您喜欢的任何分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.