我想在csv文件的一列中用完整的单词替换缩写。csv文件有两列(由管道符号分隔),有数千行,没有标题,如下所示:
c1109db0.wav|Was ist der Unterschied zwischen Gefahr und Risiko?
c112c091.wav|Die Gefahr wird z.B. in ein Risiko umgewandelt.
c11335c1.wav|Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.
我创建了一个replacers
字典,并希望将其作为df.replace()
的参数传递
我尝试了在Stackoverflow上找到的几种方法,但在创建的新文件中仍然没有替换缩写
我的代码:
import pandas as pd
def write_out_abbreviations():
"""Replace abbreviations in metadata file with full words."""
# Read file into dataframe.
with open('/home/username/data/metadata.csv') as f:
df = pd.read_csv(f, names=['Audio_Filename', 'Segment_Text'], sep='|')
# Create dictionary that contains abbreviations and their full words.
replacers = {
'bspw.': 'beispielsweise',
'bzw.': 'beziehungsweise',
' ca.': ' zirka',
'd.h.': 'das heißt',
'Dr.': 'Doktor',
' ggf.': ' gegebenenfalls',
'i.d.R.': 'in der Regel',
' inkl.': ' inklusive',
'insb.': 'insbesondere',
'Tel.': 'Telefon',
'z.B.': 'zum Beispiel'}
# Replace abbreviations in 'Segment_Text' column.
# APPROACH 1:
# df2 = df.replace({'Segment_Text': {replacers}})
# APPROACH 2:
# df2 = df['Segment_Text'].replace(replacers)
# APPROACH 3:
# df2 = df.Segment_Text.str.split()
# df2 = df.Segment_Text.apply(lambda x: ' '.join([replacers.get(e, e) for e in x]))
# APPROACH 4:
# df['Segment_Text'] = df['Segment_Text'].map(replacers).fillna(df['Segment_Text'])
# Write this dataframe to new file.
d2f.to_csv('/home/username/data/metadata_REPLACED.csv', # or df.to_csv...
header=False, index=False, sep='|')
write_out_abbreviations()
谁能告诉我我做错了什么
我很感激任何提示和提示。谢谢大家!
您正在使用正则表达式和替换函数查找^{} function :
它给出了
df2
:你可以试试这个:
样本输入:
代码:
顺便说一句,我不会在缩写中包含空格。而是把整个句子分成几个单词。然后将列表中的每个单词提供给字典,如果没有匹配项,则使用默认值
相关问题 更多 >
编程相关推荐