替换字符串列表中的子字符串

继承的怪胎

我正在尝试清理句子以及要删除句子中的这些标签的方式(它们以下划线形式,后跟一个单词,例如“ _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
G

使用正则表达式:

您可以使用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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何替换字符串列表中字符串的具体子字符串?

替换字符串列表中的字符串

从字符串列表中获取子字符串

从字符串列表中删除子字符串

替换列表中的子字符串

根据字符串列表和相应替换列表替换文件中的字符串

如何检查字符串列表中的任何字符串是否是字符串的子字符串?

Python ~ 用字符串列表项替换字符串中的字符

替换字符串列表中的 ' (APOSTROPHE)

遍历字符串列表以拉出子字符串

按子字符串排序字符串列表

用另一个子字符串替换字符串列表中的特定子字符串

如何在Python的字符串列表中的特定字符后删除子字符串

如何从可能的字符串列表中替换python中的字符串

用JSON中的字符串列表替换单词中的多个相等字符串

字符串列表中的子字符串的Python列表

用数组php中的字符串列表替换字符串

替换字符串列表中的字符串时出现“无重载版本”错误

如何使用 Python 2.7 从字符串列表中替换部分字符串

熊猫:如果字符串列表中没有该字符串,请用“其他”字符串替换

如何从 Python 中的给定字符串中删除子字符串列表?

如果子字符串在字符串列表中,则返回字符串列表

从字符串列表中删除字符串项目

从字符串列表中删除空字符串

字符串列表中的字符串长度python

在字符串列表中对字符串使用Maybe

从字符串列表中删除空字符串

如何使用Lambda在字符串列表的某些元素中执行子字符串

Python:最佳搜索字符串列表中的子字符串