簡體   English   中英

替換字符串中的特定字符

[英]Replacing a specific character in a string

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

我有類似的東西:

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

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

我也有一個字符串,比如說“ LooK at Me”,我想將其轉換為“ PooN at Se”。 我的想法是遍歷字符串的每個字母,並遍歷第一個列表,比較兩者,如果它們是匹配的,則簡單地將匹配的字符串替換為列表中的某個字母,用是清單二中的一對。

由於我正在處理大型文本,因此循環效率非常低。

我訪問的字符串實際上是熊貓數據框中的行:

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']

這里的訣竅是,我實際上正在處理用西里爾字母編寫的文本,並且我無法使用任何函數來降低大寫字母,這是我的目標。 我遇到的最好的問題是我在頂部介紹的問題,只需找到每個大寫字母並將其替換為小寫字母即可。

有什么建議嗎?

看來您需要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
#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'

您可以創建一個轉換表,並使用translate方法。

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

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

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

我們使用maketrans創建轉換表。 我們將它與to參數一起使用,即兩個長度相等的字符串。 然后,我們使用字符串的翻譯方法。

我將使用vectorized .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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM