gpt4 book ai didi

Python:拆分时如何获得正确的列表?

转载 作者:行者123 更新时间:2023-11-28 22:02:52 24 4
gpt4 key购买 nike

在test.txt中,我有2行句子。

The heart was made to be broken.
There is no surprise more magical than the surprise of being loved.

代码:

import re
file = open('/test.txt','r')#specify file to open
data = file.readlines()
file.close()
for line in data:
line_split = re.split(r'[ \t\n\r, ]+',line)
print line_split

代码的结果:

['The', 'heart', 'was', 'made', 'to', 'be', 'broken.', '']
['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.']

如何只打印word? (看第一句)期望结果:

['The', 'heart', 'was', 'made', 'to', 'be', 'broken.']
['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.']

有什么建议吗?

最佳答案

除了使用 split 来匹配定界符,您还可以使用 findall 和取反的正则表达式来匹配您想要保留的部分:

line_split = re.findall(r'[^ \t\n\r., ]+',line)

在线查看它:ideone

关于Python:拆分时如何获得正确的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10465930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com