在python中遇到了一些困难。我想把一个包含许多注释的.txt文件分割成一个列表。但是,我想对所有标点符号、空格和\n进行拆分,当我运行下面的python代码时,它会将我的文本文件分割成奇怪的地方。注意:下面我只试着在句点和尾行上分开来测试它。但它仍然经常把最后一封信用文字处理掉。
import regex as re
with open('G:/My Documents/AHRQUnstructuredComments2.txt','r') as infile:
nf = infile.read()
wList = re.split('. | \n, nf)
print(wList)发布于 2017-07-21 19:10:04
您需要修复引号,并对正则表达式做一些细微的更改:
import regex as re
with open('G:/My Documents/AHRQUnstructuredComments2.txt','r') as infile:
nf = infile.read()
wList = re.split('\W+' nf)
print(wList)发布于 2017-07-21 19:15:43
您忘记关闭字符串了,您需要在此之前。
import regex as re
with open('G:/My Documents/AHRQUnstructuredComments2.txt','r') as infile:
nf = infile.read()
wList = re.split('\. |\n |\s', nf)
print(wList)有关更多信息,请参见Split Strings with Multiple Delimiters?。
此外,RichieHindle完美地回答了您的问题:
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']发布于 2017-07-21 19:16:37
在regex中,字符.是指任何字符。你必须逃离它,\.,才能捕捉句点。
https://stackoverflow.com/questions/45245081
复制相似问题