我正在尝试将输入的文档按特定字符拆分。我需要在[和]把它们分开,但我很难搞清楚。
def main():
for x in docread:
words = x.split('[]')
for word in words:
doclist.append(word)
这是代码的一部分,将它们拆分到我的列表中。但是,它将返回文档的每一行。
例如,我想转换
['I need to [go out] to lunch', 'and eat [some food].']
到
['I need to', 'go out', 'to lunch and eat', 'some food', '.']
谢谢!
string.split(s)是您正在使用的字符串,它将“s”的整个内容视为分隔符。换言之,你的输入应该看起来像“[]我需要出去吃午饭”,“吃点东西给你想要的结果”。
您需要使用re module中的split(s),它将把s视为regex
您可以尝试使用
re.split()
代替:看起来很奇怪的正则表达式
[\[\]]
是一个字符类,它意味着在上拆分[
或]
。内部\[
和\]
必须是反斜杠转义,因为它们使用与[
和]
相同的字符来包围字符类。str.split()
在传递给它的精确字符串处拆分,而不是在它的任何字符处拆分。传递"[]"
将在出现[]
时拆分,但不会在单个括号中拆分。可能的解决方案是拆分两次:
使用
re.split()
。相关问题 更多 >
编程相关推荐