[英]Replacing a specific character if it is inside a string that matches a pattern in Python
[英]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'
我將使用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.