【发布时间】:2020-04-17 16:13:55
【问题描述】:
我有一个熊猫数据框中的化学反应列表,我想将其拆分为它们的成分。方程式并不复杂,这里有几个例子:
N2 + CH4 → HCN + NH3
H2+F2→2HF
目标是在 + 和 → 上拆分字符串并得到以下内容
['N2','CH4','HCN','NH3]
[H2,'F2','HF']
这是我目前所拥有的
import re
df = pd.read_csv("foo.csv") # read the csv file
convert=df['Reaction'].to_string() # convert the reaction column to a string object
result = re.split(r'(\+ →)',convert) # attempt to split on the two delimiters
# alternatively I have tried replacing the right arrow with its unicode equivalent like this
# result = re.split(r'\+\u2192)',convert)
每次我运行这段代码时,我都会得到相同的字符串,没有任何变化。
我还尝试将列保留为列表对象而不是字符串对象,然后
试图拆分它,当我这样做时,我得到Type Error: Expected string or bytes-like object
【问题讨论】:
-
您可以使用字符类代替
[+ →]+请参阅ideone.com/xKRi3c -
你也许可以在
\W+上拆分
标签: regex python-3.x pandas