首页 > 解决方案 > 它不是在 python 字符串中

问题描述

我的 python 字符串由'而不是 ' (单引号)组成。我目前的目标是扩展复合词,例如 It's to It is, Haven't to Have not。

“这对我来说很棒。我已经使用了 2 周,上周我只出现了 3 次头痛,服用 2 次泰诺就消失了。我每天都有慢性头痛,而且不会消失“不管我吃了什么。我白天还是有点困,但我知道会好起来的。”

上面的陈述是我一直试图转换的句子的一个例子。

有人可以建议一种将其转换为字符串格式的方法吗?

标签: pythonstringsingle-quotes

解决方案


text = "This has been great for me. I've been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that wouldn't go away no matter what I took. I'm still a little sleepy during the day, but I know that will get better."
d_contraction = {"I'm":"I am","wouldn't":"would not","I've":"I have"}
updated_text = text.replace(''', "'") 
print(updated_text)
for k,v in d_contraction.items():
    updated_text = updated_text.replace(k,v) 
print(updated_text)

输出:

This has been great for me. I've been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that wouldn't go away no matter what I took. I'm still a little sleepy during the day, but I know that will get better.

This has been great for me. I have been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that would not go away no matter what I took. I am still a little sleepy during the day, but I know that will get better.

上面的代码适用于您提供的文本。基本上,您将必须创建一个包含所有可能的收缩示例的字典——它们会、它们等等。


推荐阅读