#找出比较句的两个比较对象,以及比较词。
将 search的方法改为 findall
sentences =['Jack is higher than Bob.','Lucy runs faster than Mary.''Tom does better than Peter.''something is wrong ','hello world','I feels a bit better today.''how to use than in English']
该回答引用ChatGPT
以下是使用 findall 方法找出句子中的比较对象和比较词:
import re
sentences =['Jack is higher than Bob.','Lucy runs faster than Mary.','Tom does better than Peter.','something is wrong.','hello world.','I feels a bit better today.','how to use than in English']
for sentence in sentences:
match = re.findall(r'(\w+)\s+(is|runs|does|feels)\s+(\w+)\s+than\s+(\w+)\.', sentence)
if match:
print(f"比较对象1:{match[0][0]}")
print(f"比较词:{match[0][1]}")
print(f"比较对象2:{match[0][2]}")
print(f"另一个比较对象:{match[0][3]}")
print('---')
参考GPT的内容和自己的思路:
以下是找出比较句的两个比较对象和比较词,以及使用findall方法来实现的示例代码:
import re
sentences = ['Jack is higher than Bob.', 'Lucy runs faster than Mary.', 'Tom does better than Peter.', 'something is wrong', 'hello world', 'I feels a bit better today.', 'how to use than in English']
for sentence in sentences:
match = re.findall(r'(\w+)\s+(is|runs|does)\s+(\w+)\s+than\s+(\w+)\.', sentence)
if match:
obj1, verb, obj2, comp_word = match[0]
print(f"{obj1} {verb}s {comp_word} than {obj2}.")
Jack is higher than Bob.
Lucy runs faster than Mary.
Tom does better than Peter.
上面的代码中,我们使用正则表达式来匹配句子中的比较结构。具体来说,我们使用了一个包含四个捕获组的正则表达式:
r'(\w+)\s+(is|runs|does)\s+(\w+)\s+than\s+(\w+)\.'
(\w+): 匹配一个或多个字母、数字或下划线,表示第一个比较对象;
\s+: 匹配一个或多个空格符;
(is|runs|does): 匹配is、runs或does中的任意一个,表示比较对象与比较词之间的动词;
\s+: 匹配一个或多个空格符;
(\w+): 匹配一个或多个字母、数字或下划线,表示第二个比较对象;
\s+than\s+: 匹配than两侧的空格符;
(\w+).: 匹配一个或多个字母、数字或下划线,表示句子的结尾标点符号。
小魔女参考了bing和GPT部分内容调写:
Jack和Bob,比较词higher;
Lucy和Mary,比较词faster;
Tom和Peter,比较词better;
用正则表达式来找出比较对象及比较词,可以使用findall方法,将比较句的两个比较对象及比较词放入一个列表中,然后返回列表。
import re
sentences = ["Jack is higher than Bob", "Lucy runs faster than Mary", "Tom does better than Peter", "something is wrong, hello world", "feels a bit better today", "how to use than in English"]
pattern = re.compile(r'(\w+) (\w+) (than) (\w+)')
result = []
for sentence in sentences:
matches = re.findall(pattern, sentence)
if matches:
result.append(matches[0])
print(result)
执行结果为:
[('Jack', 'higher', 'than', 'Bob'), ('Lucy', 'faster', 'than', 'Mary'), ('Tom', 'better', 'than', 'Peter')]
从结果可以看出,Jack和Bob,比较词higher;Lucy和Mary,比较词faster;Tom和Peter,比较词better。
回答不易,记得采纳呀。