替换字符串列表中的子字符串
Posted
技术标签:
【中文标题】替换字符串列表中的子字符串【英文标题】:Replace Substring in a List of String 【发布时间】:2017-06-22 08:18:40 【问题描述】:我正在尝试清理我的句子以及我想在我的句子中删除这些标签的内容(它们的形式是下划线,后跟一个单词,例如“_UH”)。 基本上我想删除后跟下划线的字符串(也删除下划线本身)
文本:
['hanks_NNS sir_VBP',
'Oh_UH thanks_NNS to_TO remember_VB']
需要输出:
['hanks sir',
'Oh thanks to remember']
以下是我试过的代码:
for i in text:
k= i.split(" ")
print (k)
for z in k:
if "_" in z:
j=z.replace("_",'')
print (j)
电流输出:
ThanksNNS
sirVBP
OhUH
thanksNNS
toTO
rememberVB
RemindVB
【问题讨论】:
【参考方案1】:使用正则表达式:
您可以使用re.sub()
完成此操作。匹配字符串中想要的子字符串,并将子字符串替换为空字符串:
import re
text = ['hanks_NNS sir_VBP', 'Oh_UH thanks_NNS to_TO remember_VB']
curated_text = [re.sub(r'_\S*', r'', a) for a in text]
print curated_text
输出:
['hanks sir', 'Oh thanks to remember']
正则表达式:
_\S* - Underscore followed by 0 or more non space characters
没有正则表达式:
text = ['hanks_NNS sir_VBP', 'Oh_UH thanks_NNS to_TO remember_VB']
curated_text = [] # Outer container for holding strings in text.
for i in text:
d = [] # Inner container for holding different parts of same string.
for b in i.split():
c = b.split('_')[0] # Discard second element after split
d.append(c) # Append first element to inner container.
curated_text.append(' '.join(d)) # Join the elements of inner container.
#Append the curated string to the outer container.
print curated_text
输出:
['hanks sir', 'Oh thanks to remember']
您的代码有问题:
实际上你想用空字符串替换'_'
和它后面的字符时,你只是用空字符串替换'_'
。
for i in text:
k= i.split(" ")
print (k)
for z in k:
if "_" in z:
j=z.replace("_",'') # <--- 'hanks_NNS' becomes 'hanksNNS'
print (j)
【讨论】:
以上是关于替换字符串列表中的子字符串的主要内容,如果未能解决你的问题,请参考以下文章
将双括号内的子字符串替换为javascript中的不同字符串