任务是在段落中找到首字母缩写词,规则是指定两个或多个连续的大写字母(例如IT)作为首字母缩写词,但是首字母缩写词加上连字符加小写字母(例如ASS-kee)不能被视为任务,但ASS-AS是首字母缩写。我的问题是,如果我想找到带有连字符的缩写词(例如ASS-AS),就不能排除ASS-kee这样的词。 我的代码是:
s = 'ASCII (/ˈæskiː/ ASS-kee),[2]:6 abbreviated from American Standard Code \
for Information Interchange, is a character encoding standard for electronic \
communication. ASCII codes represent text in computers, telecommunications \
equipment, and other devices. The Internet Assigned Numbers Authority (IANA) \
prefers the name US-ASCII for this character encoding.'
print(re.findall(r'\b[A-Z]+\-[A-Z]+\b|\b[a-z]*[A-Z]{2,}\b',s))
答案 0 :(得分:0)
\b
字符与非消耗性单词边界匹配,例如字母后的连字符,因此您需要从-
中排除\b
。
不幸的是,这个排除并不是一件容易的事,因为它取决于正则表达式的风格。 (我认为)在所有地方都可以使用的一种方法是将负向超前与((?!-)\b)
一起使用。
因此将其组成您的表情
\b[A-Z]+-[A-Z]+\b|\b[A-Z]+(?!-)\b
应该做的事
答案 1 :(得分:0)
Python中findall
的结果会有所不同,具体取决于模式中组的存在。这是您的问题的有效示例:
import re
s = 'ASCII (/ˈæskiː/ ASS-kee),[2]:6 abbreviated from American Standard Code \
for Information Interchange, is a character encoding standard for electronic \
communication. ASCII codes represent text in computers, telecommunications \
equipment, and other devices. The Internet Assigned Numbers Authority (IANA) \
prefers the name US-ASCII for this character encoding.'
m = re.findall(r'(\b[A-Z]{2,}(-[A-Z]+)+|\b[A-Z]{2,}(?!-)\b)',s)
result = [i[0] for i in m]
print(result)
我更新了您的正则表达式以满足您的需求,并且还向您展示了如何获得所需的结果。诀窍是已经提到的@PA中的超前断言。您可以详细了解here。结果是此列表顺便说一句:
['ASCII', 'ASCII', 'IANA', 'US-ASCII']