如何在句子列表中的单词和开口括号之间创建一个空格。

问题描述 投票:0回答:1

在下面的列表中,实际上有两个重复的句子。但是由于句子的第二个词和(之间的空格不同,它将它们视为唯一的句子。

通过使用Python - 正则表达式,如何在单词之间创建加法空格。(例如:第 1 项)'United States(US)',应该改为'United States(US)'(与第 2 项相同)

listx = 
['United States(US)',
 'United States (US)',
 'New York(NY)',
 'New York (NY)']

预期输出列表是

['United States (US)',
 'United States (US)',
 'New York (NY)',
 'New York (NY)']

事实上,我正在尝试从列表中消除重复的句子,并考虑这是一个方法,先让句子相似。请给我建议。

python regex list nltk re
1个回答
3
投票

你可以搜索一个字母后面紧跟着一个开放的小括号。

>>> [re.sub(r'(\w)\(', r'\1 (', i) for i in listx]
['United States (US)',
 'United States (US)',
 'New York (NY)',
 'New York (NY)']

要删除重复的内容,您可以创建一个 set 从这个生成表达式中

>>> set(re.sub(r'(\w)\(', r'\1 (', i) for i in listx)
{'United States (US)', 'New York (NY)'}

1
投票

你可以试试这个。你可以用 re.sub 这里。

listx = ['United States(US)', 'United States (US)', 'New York(NY)', 'New York (NY)']

[re.sub(r'.(\(.*\))',r' \1',i) for i in listx]
# ['United State (US)', 'United States (US)', 'New Yor (NY)', 'New York (NY)']

Regex模式解释。

  • . 匹配任何字符
  • ( 大括号
  • \( 匹配 (
  • .* 贪婪地匹配。
  • ' \1' 子匹配组与空间匹配组。
  • regex live demo

0
投票

您可以做

    new_listx = ["{} {}".format(re.match('(.*)(\(.*\))', i).group(1).rstrip() ,re.match('(.*)(\(.*\))', i).group(2)) for i in listx]
    print(new_listx)

产量

['United States (US)', 'United States (US)', 'New York (NY)', 'New York (NY)']

该regex将文本分割成两组,一组在()之前,第二组在()中,之后它将修剪第一组右边的空格。

print(set(new_listx))

你会得到一个独特的值集。

{'New York (NY)', 'United States (US)'}
© www.soinside.com 2019 - 2024. All rights reserved.