替换字符串中的特定字符

时间:2017-04-29 07:03:29

标签: python string pandas dataframe

这可能是非常基本的,但我一直在努力。

我有类似的东西:

one = ['L', 'K', 'M']

two = ['P', 'N', 'S']

我也有一个字符串,让我们说它类似于" LooK at Me&#34 ;,我想转换成" PooN at Se"。我的想法是循环遍历字符串的每个字母,并循环通过第一个列表,比较两个,如果它们匹配,只需替换字符串中与列表中的内容匹配的字母一个与它在第二列中的配对。

循环被证明是非常低效的,因为我正在处理大文本。

我正在访问的字符串实际上是pandas数据帧中的行:

data = pd.read_csv('train.txt', delimiter='\t', header=None, names=['category', 'text'], dtype=str)

print data.head()给出了类似的内容:

0 MUSIC Today at the recording studio, John... 1 POLITICS The tensions inside the government have... 2 NEWS The new pictures of NASA show...

我将文字分开,如

text = data['text']

这里的诀窍是,我实际上正在使用用西里尔语编写的文本,我不能使用任何函数来降低大写字母,这是我的目标。我最好的问题是我在顶部介绍的问题,只需找到每个大写字母并用它的小写字母替换它。

有任何建议吗?

4 个答案:

答案 0 :(得分:2)

您似乎需要replace

print (data)
                                                text
0         MUSIC  Today at the recording studio, John
1  POLITICS  The tensions inside the government have
2                NEWS  The new pictures of NASA show

one = ['L', 'K', 'M']
two = ['P', 'N', 'S']
data['text'] = data['text'].replace(one, two, regex=True)
print (data)
                                                text
0         SUSIC  Today at the recording studio, John
1  POPITICS  The tensions inside the government have
2                NEWS  The new pictures of NASA show

答案 1 :(得分:1)

#use list comprehension
''.join([e if e not in one else two[one.index(e)] for i,e in enumerate(s)])
Out[523]: 'PooN at Se'

答案 2 :(得分:1)

您可以创建转换表,并使用translate方法。

translation_table = str.maketrans("ABÉПЯ", "abéпя")

text = "Éléphant Язы́к"

text.translate(translation_table)
# 'éléphant язы́к'

我们使用maketrans来创建转换表。我们将它用于参数,两个相等长度的字符串。 然后我们使用字符串的translate方法。

答案 3 :(得分:1)

我使用了矢量化.str.translate()方法,专门用于此类方法:

In [62]: one = ['S','o','a']

In [63]: two = ['$', '0', '@']

In [64]: tran_tab = str.maketrans(''.join(one), ''.join(two))

In [65]: data.text.str.translate(tran_tab)
Out[65]:
0           MU$IC  T0d@y @t the rec0rding studi0, J0hn
1    POLITIC$  The tensi0ns inside the g0vernment h@ve
2                  NEW$  The new pictures 0f NA$A sh0w
Name: text, dtype: object
相关问题