繁体   English   中英

使用特定字符在Python中拆分字符串

[英]Splitting strings in Python using specific characters

我正在尝试将输入的文档拆分为特定字符。 我需要将它们拆分为[和],但我很难搞清楚这一点。

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', '.']

谢谢!

您可以尝试使用re.split()代替:

>>> import re
>>> re.split(r"[\[\]]", "I need to [go out] to lunch")
['I need to ', 'go out', ' to lunch']

奇数找正则表达式[\\[\\]]是一个字符类,它是指在分裂[] 内部\\[\\]必须反斜杠转义,因为它们使用与[]相同的字符来包围字符类。

str.split()按照传递给它确切字符串进行拆分,而不是它的任何字符。 传递"[]"将在[]出现时分开,但不会在单个括号中分开。 可能的解决方案

  1. 分裂两次:

     words = [z for y in x.split("[") for z in y.split("]")] 
  2. 使用re.split()

string.split(s),您正在使用的那个,将's'的整个内容视为分隔符。 换句话说,你输入应该看起来像“[]'我需要[]出去[]吃午餐',然后吃[]一些食物[]。'[]”为它给你结果你想。

您需要使用re模块中的 split(s),它将s视为正则表达式

import re

def main():
for x in docread:
    words = re.split('[]', x)
    for word in words:
        doclist.append(word)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM