拼接字符串

2024-10-03 19:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想看看是否有一种好方法可以用以下文本场景填充字典:

(1) The company owns the target.
(2) The accounts are: (a) true and fair; (b) not misleading.
(3) The company is not a party to any litigation.

(1)和(3)很容易分开,但(2)是我正在努力解决的问题。理想情况下,它应该是“账目真实且公平”/“账目没有误导”,这需要一些拼接,然后重新组合字符串

我想出了下面的答案,但我不认为这是直截了当的,我相信有更好的答案

w = "(1) The accounts are:\n (a) true and fair;\n (b) not misleading."
x = re.findall('^[(].[)](.+)[:]', w)
y = re.findall('[(a-z)]\s(.+)[;]', w)
z = re.findall('[(a-z)]\s(.+)[.]', w)
print(x + y)
print(x + z)

Tags: andthe方法答案retruefairnot
2条回答

如果我理解正确,当文本中仅出现两个“选项”中的一个,即仅“真实和公平”或仅“不误导”时,您也希望匹配

正则表达式中的一个问题是[(a-z)]没有做您认为它做的事情。这样的类只匹配一个字符。所以你想要的是:\([a-z]\)

以下是如何让它工作:

w = "(1) The accounts are:\n (a) true and fair;\n (b) not misleading."
res = re.findall(r"\(\d\)\s(.*):$\s*\([a-z]\)(.*?)(?:\.|;$\s*\([a-z]\)(.*?)\.)$", w, re.MULTILINE)

for a, b, c in res:
    print(a + b)
    if c:
        print(a + c)

看看这个

import re
s ="(1) The accounts are:\n (a) true and fair;\n (b) not misleading."
match =re.findall(r' [\w\s]+',h)
match
# -> [' The accounts are', ' true and fair', ' not misleading']

match = list(map(lambda x: x.strip(),match))
match
# -> ['The accounts are', 'true and fair', 'not misleading']

x = ' '.join([match[0], match[1]])
y = ' '.join([match[0], match[2]])
x,y
# -> ('The accounts are true and fair', 'The accounts are not misleading')

相关问题 更多 >