【发布时间】:2020-11-03 02:28:38
【问题描述】:
我有一个数据框(我们称其为“小文本”),其中有一列,每行包含句子。我还有另一个表(我们称之为“littledict”),我想将其用作在“littletext”的每一行中查找和替换单词和/或短语的参考。
这是我的两个数据框。我在这个例子中对它们进行了硬编码,但会在“现实生活”中将它们加载为 csv 文件:
raw_text = {
"text": ["Hello, world!", "Hello, how are you?", "This world is funny!"],
"col2": [0,1,1]}
littletext = pd.DataFrame(raw_text, index = pd.Index(['A', 'B', 'C'], name='letter'), columns = pd.Index(['text', 'col2'], name='attributes'))
raw_dict = {
"key": ["Hello", "This", "funny"],
"replacewith": ["Hi", "That", "hilarious"]}
littledict = pd.DataFrame(raw_dict, index = pd.Index(['a','b','c'], name='letter'), columns = pd.Index(['key', 'replacewith'], name='attributes'))
print(littletext) # ignore 'col2' since it is irrelevant in this discussion
text col2
A Hello, world! 0
B Hello, how are you? 1
C This world is funny! 1
print(littledict)
key replacewith
a Hello Hi
b This That
c funny hilarious
我想按照下面的方式修改“小文本”,其中 Python 将在我的“小文本”表(数据框)的每个句子中查看多个单词并替换多个单词,作用于所有行。最终的结果应该是 A 行和 B 行中的 'Hello' 被替换为 'Hi',并且 C 行中的 'That' 被替换为 'This' 并且 'funny' 被替换为 'hilarious':
text col2
A Hi, world! 0
B Hi, how are you? 1
C That world is hilarious! 1
这是我尝试过的两次尝试,但都没有奏效。他们没有产生错误,他们只是没有像我上面描述的那样修改“小文本”。尝试#1“技术上”有效,但它效率低下,因此对于大规模工作毫无用处,因为我必须预测和编程我需要替换其他句子的每一个可能的句子。尝试 #2 根本没有改变任何东西。
我的两个不起作用的尝试是:
尝试#1:这没有帮助,因为要使用它,我必须编写整个句子来替换其他句子,这是没有意义的:
littltext['text'].replace({'Hello, world!': 'Hi there, world.', 'This world is funny!': 'That world is hilarious'})
尝试 #1 返回:
Out[125]:
0 Hi there, world.
1 Hello, how are you?
2 That world is hilarious
Name: text, dtype: object
尝试 #2:此尝试更接近标记,但没有返回任何更改:
for key in littledict:
littletext = littletext.replace(key,littledict[key])
尝试 #2 返回:
text col2
0 Hello, world! 0
1 Hello, how are you? 1
2 This world is funny! 1
我搜索了互联网,包括 Youtube、Udemy 等,但无济于事。许多“教程”站点仅涵盖单个文本示例,而不是像我展示的示例那样的整列句子,因此在扩展到行业规模的项目时毫无用处。我希望有人能慷慨地阐明这一点,因为这种文本操作在许多行业环境中很常见。
我对任何可以提供帮助的人表示衷心的感谢和感谢!
【问题讨论】:
-
请提供预期的[最小的、可重现的示例](stackoverflow.com/help/minimal-reproducible-example)。您发布的代码无法运行;你没有显示结果。您的第二次尝试已接近...
-
感谢您的提醒 ;-) 完成。
-
未完成。您发布的代码仍然无法运行。除非您的输入有问题,否则它不应该出现在帖子中。硬编码你的 DF 和 dict。
-
对我的问题进行了调整。如果有人发现任何问题,请告诉我。再次感谢大家!
标签: python pandas string text replace