Python在空格上拆分,除了单词之间和逗号之后

2024-10-03 13:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想分成以下几部分

11/27/2019 Sold $900,000 -6.2% Suzanne Freeze-Manning, Kevin Garvey

11/2/2019 Pending sale $959,000

进入

['11/27/2019', 'Sold', '$900,000', '-6.2%', 'Suzanne Freeze-Manning, Kevin Garvey']
['11/2/2019', 'Pending sale', '$959,000']

我试过使用regex,但是没有找到一个能够完成拆分的re.split()组合,除了单词之间和逗号之后。你知道吗

我怎样才能做到这一点?你知道吗


Tags: resale单词regexsplit逗号freezekevin
3条回答

你从哪里得到你的数据?是CSV吗?你能把分隔符改成逗号或别的什么吗?你知道吗

现在只能使用空格作为分隔符。你知道吗

例如:

>>> x = '11/27/2019 Sold $900,000 -6.2% Suzanne Freeze-Manning, Kevin Garvey'
>>> x.split(" ")
['11/27/2019', 'Sold', '$900,000', '-6.2%', 'Suzanne', 'Freeze-Manning,', 'Kevin
', 'Garvey']

注意,它切掉了字符串“苏珊·弗雷兹·曼宁,凯文·加维”

如果将选项卡用作分隔符,则可以轻松执行以下操作:

例如:

>>> x = '11/27/2019\tSold\t$900,000\t-6.2%\tSuzanne Freeze-Manning, Kevin Garvey'
>>> print(x)
11/27/2019  Sold    $900,000    -6.2%   Suzanne Freeze-Manning, Kevin Garvey
>>> x.split("\t")
['11/27/2019', 'Sold', '$900,000', '-6.2%', 'Suzanne Freeze-Manning, Kevin Garvey']

或者,如果您总是有5列数据,比如第一个字符串,您可以告诉它在第四次迭代后停止拼接。你知道吗

例如:

>>> x.split(" ",4)
['11/27/2019', 'Sold', '$900,000', '-6.2%', 'Suzanne Freeze-Manning, Kevin Garvey']

有关分隔符的详细信息,请参见https://docs.python.org/3.6/library/stdtypes.html#str.split。你知道吗

请尝试以下代码:

import re
l = '11/27/2019 Sold $900,000 -6.2% Suzanne Freeze-Manning, Kevin Garvey'

l = l.replace(" ", '&')  # replace the & for a character that you are ensure that won't be in you string

l = l.replace(',&', ', ') # This ensures the maintence of the "after comma words"

result = re.sub(r'([^0-9, %])&([^0-9, $])', r'\1 \2', l) # Now every white space is a & char, you know that it must be splited if the previous item is a number (price in this case) a percentage symbol, the next word should be the $ (also indicating the price), or a number. If the pattern does't follow this rules, it is considered a word that won't be splited. Note, the code replace just the & ('after words' and 'after commas) for ' ' and keep the rest of the regex pattern intact. 

result = result.split('&') # Now just the itens that must be splited has the & between them. 

print(result)

您可以使用此正则表达式,它查找前面没有字母或逗号,或者后面没有字母的空格:

(?<![a-z,]) | (?![a-z])

Demo on regex101

在python中:

import re
a = "11/27/2019 Sold $900,000 -6.2% Suzanne Freeze-Manning, Kevin Garvey"
b = "11/2/2019 Pending sale $959,000"

print(re.split(r'(?<![a-z,]) | (?![a-z])', a, 0, re.IGNORECASE))
print(re.split(r'(?<![a-z,]) | (?![a-z])', b, 0, re.IGNORECASE))

输出:

['11/27/2019', 'Sold', '$900,000', '-6.2%', 'Suzanne Freeze-Manning, Kevin Garvey']
['11/2/2019', 'Pending sale', '$959,000']

相关问题 更多 >