【问题标题】:Seperating a python string by character while keeping inline tags intact在保持内联标签完整的同时按字符分隔 python 字符串
【发布时间】:2021-03-17 00:02:48
【问题描述】:

我正在尝试在 python 中制作一个与内联标签一起使用的自定义标记器。目标是接受这样的字符串输入:

'This is *tag1* a test *tag2*.'

并让它输出一个由标签和字符分隔的列表:

['T', 'h', 'i', 's', ' ', 'i', 's', ' ', '*tag1*', ' ',  'a', ' ', 't', 'e', 's', 't', ' ', '*tag2*', '.']

没有标签,我只会使用list(),我想我找到了一个解决方案来处理单个标签类型,但有多个。还有其他多字符段,例如椭圆,应该被编码为单个特征。
我尝试的一件事是用正则表达式用一个未使用的字符替换标签,然后在字符串上使用list()

text = 'This is *tag1* a test *tag2*.'
tidx = re.match(r'\*.*?\*', text)
text = re.sub(r'\*.*?\*', r'#', text)
text = list(text)

然后我将对其进行迭代并用提取的标签替换“#”,但我有多个不同的特征要尝试提取,并且在拆分字符串之前使用不同的占位符字符多次重复该过程似乎是不好的做法.有没有更简单的方法来做这样的事情?我对此还是很陌生,所以还有很多我不知道的常用方法。我想我也可以使用一个更大的正则表达式,它包含我试图提取的所有特征,但它仍然感觉很hacky,我更喜欢使用更模块化的东西,可以用来查找其他特征而无需编写新的表达式每次。

【问题讨论】:

  • 看看词法扫描器,为你的文本编写一个语法,它会为你解析它,或者编写你自己的状态机

标签: python regex nlp data-cleaning


【解决方案1】:

我不确定哪种方法最适合您,但您应该能够使用下面展示的 split() 方法或 .format() 方法来获得您想要的。

# you can use this to get what you need
txt = 'This is *tag1* a test *tag2*.'
x = txt.split("*") #Splits up at *
x = txt.split() #Splits all the words up at the spaces
print(x)

# also, you may be looking for something like this to format a string
mystring = 'This is {} a test {}.'.format('*tag1*', '*tag2*')
print(mystring)


# using split to get ['T', 'h', 'i', 's', ' ', 'i', 's', ' ', '*tag1*', ' ',  'a', ' ', 't', 'e', 's', 't', ' ', '*tag2*', '.']
txt = 'This is *tag1* a test *tag2*.'
split = txt.split("*") #Splits up at *

finallist = [] # initialize the list
for string in split:

    # print(string)
    if string == '*tag1*':
        finallist.append(string)
        # pass
    elif string == '*tag2*.':
        finallist.append(string)

    else:
        for x in range(len(string)):
            letter = string[x]
            finallist.append(letter)

print(finallist)

【讨论】:

    【解决方案2】:

    您可以将以下正则表达式与re.findall 一起使用:

    \*[^*]*\*|.
    

    请参阅regex demore.Sre.DOTALL 标志可以与此模式一起使用,以便 . 也可以匹配默认情况下不匹配的换行符。

    详情

    • \*[^*]*\* - 一个* 字符,后跟零个或多个除* 以外的字符,然后是*
    • | - 或
    • . - 任何一个字符(带有re.S)。

    Python demo

    import re
    s = 'This is *tag1* a test *tag2*.'
    print( re.findall(r'\*[^*]*\*|.', s, re.S) )
    # => ['T', 'h', 'i', 's', ' ', 'i', 's', ' ', '*tag1*', ' ', 'a', ' ', 't', 'e', 's', 't', ' ', '*tag2*', '.']
    

    【讨论】:

    • 这似乎运作良好。我没有扩展表达式以处理省略号和其他特征,而是使用了几个正则表达式函数将所有这些函数转换为遵循星号方案的标签,所以一切都应该正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多