Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫替换为字典';不适用于CSV文件_Python_Pandas_Dictionary_Replace - Fatal编程技术网

Python 熊猫替换为字典';不适用于CSV文件

Python 熊猫替换为字典';不适用于CSV文件,python,pandas,dictionary,replace,Python,Pandas,Dictionary,Replace,我想在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.

我想在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.
我创建了一个
replaces
字典,并希望将其作为
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()
import pandas as pd
df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
 'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
  1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
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'}

df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))

# Out[158]:
# 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
# 1    Ein Sturz das heißt ein Fall von der Kante ist...
# Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
谁能告诉我我做错了什么

我很感激任何提示和提示。谢谢大家!

您可以尝试以下方法:

样本输入:

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()
import pandas as pd
df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
 'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
  1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
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'}

df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))

# Out[158]:
# 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
# 1    Ein Sturz das heißt ein Fall von der Kante ist...
# Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
代码:

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()
import pandas as pd
df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
 'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
  1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
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'}

df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))

# Out[158]:
# 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
# 1    Ein Sturz das heißt ein Fall von der Kante ist...
# Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
顺便说一句,我不会在缩写中包含空格。而是把整个句子分成几个单词。然后将列表中的每个单词提供给词典,如果不匹配,则使用默认值。

您可以尝试以下操作:

样本输入:

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()
import pandas as pd
df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
 'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
  1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
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'}

df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))

# Out[158]:
# 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
# 1    Ein Sturz das heißt ein Fall von der Kante ist...
# Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
代码:

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()
import pandas as pd
df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
 'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
  1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
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'}

df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))

# Out[158]:
# 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
# 1    Ein Sturz das heißt ein Fall von der Kante ist...
# Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
顺便说一句,我不会在缩写中包含空格。而是把整个句子分成几个单词。然后将列表中的每个单词提供给字典,如果不匹配,则使用默认值。

您正在使用正则表达式和替换函数查找:

rx = re.compile('|'.join(replacers.keys()))
df2 = df['Segment_Text'].str.replace(rx, lambda m: replacers[m.group(0)])
对于
df2
,它给出:

0    Was ist der Unterschied zwischen Gefahr und Ri...
1    Die Gefahr wird zum Beispiel in ein Risiko umg...
2    Ein Sturz das heißt ein Fall von der Kante ist...
Name: Segment_Text, dtype: object
您正在使用正则表达式和替换函数查找:

rx = re.compile('|'.join(replacers.keys()))
df2 = df['Segment_Text'].str.replace(rx, lambda m: replacers[m.group(0)])
对于
df2
,它给出:

0    Was ist der Unterschied zwischen Gefahr und Ri...
1    Die Gefahr wird zum Beispiel in ein Risiko umg...
2    Ein Sturz das heißt ein Fall von der Kante ist...
Name: Segment_Text, dtype: object

请考虑下一次提供英语样本输入,英语站点也是如此。请考虑下次提供英语样本输入,英语站点也是如此。不幸的是,在我的结尾,它仍然不起作用。我不知道为什么不,也许错在别的地方。新文件已创建,没有错误,但缩写仍然存在。您必须设置
df.iloc[:,1]=df.iloc[…
我调整了我的答案以使它更清楚。啊,当然!谢谢你指出这一点!现在它起作用了:-)嗯,不幸的是,它在我这边仍然不起作用。我不知道为什么不起作用,也许错误在其他地方。新文件已经创建,没有错误,但缩写仍然存在。你必须设置
df.iloc[:,1]=df.iloc[…
我调整了我的答案以使它更清晰。啊,当然!谢谢你指出这一点!现在它起作用了:-)