替换数据框中出现撇号的文本时出现的问题

2024-09-29 01:29:39 发布

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

我使用的是Pandas数据框,我从Excel中读取了该数据框,并希望查找和替换文本中的收缩(例如,不要->;不要)。 我使用的代码在替换不包含撇号的文本时有效,但在包含撇号的单词上无效

我已经定义了一个字典来指定要进行的替换。我在下面提供了一个示例,以及执行替换的代码

contractions_dict = { 
'ain\'t': 'is not', 'aren\'t': 'are not', 'can\'t': 'can not', '\'cause': "because",
'coz': "because", 'cos': "because", 'could\'ve': "could have", 'couldn\'t': "could not",
'didn\'t': "did not", 'doesn\'t': "does not", 'don\'t': 'do not',
'no contractions': 'TEST'
}

regex_dict = {r"(\b){}(\b)".format(k):r"\1{}\2".format(v) for k,v in contractions_dict.items()}
regex_dict


data = {'Text_with_contractions': ['Text with no contractions', "Text with contractions doesn't work", 'More text']}
df = pd.DataFrame(data)

df['Text_with_no_contractions'] = df['Text_with_contractions'].replace(regex_dict, regex=True)
df['Text_with_contractions'].iloc[1]

奇怪的是,当我在手动创建的数据框上测试时,上面的代码可以工作,但在我从Excel读入的数据框上不工作。你知道为什么吗

这是它使用的手动创建的数据帧:

data = {'Text_with_contractions': ['Text with no contractions', "Text with contractions doesn't work", 'More text']}
df = pd.DataFrame(data)

这是我在数据帧中读取的代码,它不工作:

df = pd.read_excel(path + "output.xlsx", encoding = "UTF-8")

我尝试在撇号之前使用转义字符(如上所述)。 我试过用双引号和单引号来表示撇号

如果有人能帮我找出为什么不能使用Excel读取数据并提出解决方案,我将不胜感激


Tags: 数据no代码textdfdatawithnot