在pandas中的字母和日语字符串的组合后面加上括号

2024-04-20 15:47:35 发布

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

我有一些数据在数据帧中看起来像这样:

Japanese
--------
明日|Adverb の 天気|Weather は なんですか

这里,明気标有副词,天気标有天气。你知道吗

使用Pandas和regex,我正在寻找一种方法,在有日语、pipe和英语的字符周围附加{},而不仅仅是在日语周围。 我尝试使用正则表达式,但始终出现语法错误:

df.['Japanese'] = df['Japanese'].str.append('(.+?\|[A-Za-z_]+)\', '{(.+?\|[A-Za-z_]+)}')

所需的输出如下(也在寻找一种同时删除所有空格的方法…如果这不可能,我可以在以后这样做):

Japanese
--------
{明日|Adverb}の{天気|Weather}はなんですか

谢谢!你知道吗


Tags: 数据方法pandasdf字符regex天气weather
2条回答

你可以使用^{}

df['Japanese'] = df['Japanese'].str.replace(r'(\w*\|[a-zA-Z]+)', r'{\1}', regex=True)   

# To remove white space use
df.Japanese.str.replace('\s',"", regex=True, inplace=True) 

# Output:

0    {'明日|Adverb'}の{'天気|Weather'}はなんですか
Name: Japanese, dtype: object

我想你想要这个

df['Japanese'].replace(r'(.+?\|[A-Za-z_]+)','{\g<0>}', inplace=True, regex=True)

\g<0>是对()中的组的引用

不幸的是,我不知道如何替换一行中的空格,所以在这之后你想这样做

df['Japanese'].replace('\s','', inplace=True,regex=True)

相关问题 更多 >