我必须用python来完成这个任务:选择数据框架列中不包含一个或多个字母、空格和句点的所有单词。我尝试了这段代码,但它告诉我模式是不正确的:
import re
countries = gapminder['country']
# Pattern that contains all words that do not satisfied the specification
pattern = re.compile('[a-zA-Z \.]+')
mask = countries.str.contains(pattern)
# Select the complement of mask
invalid_countries = countries[~mask]
print(invalid_countries)发布于 2020-01-06 20:25:28
你可以用
invalid_countries = countries.str.contains(r'^[^a-zA-Z.\s]+$')正则表达式是^[^a-zA-Z.\s]+$
^ - string[^a-zA-Z.\s]+ -1或更多字符的开头(字母、.、whitespace$除外)-字符串的结尾。发布于 2020-01-06 19:46:38
您正在使用contains,它将查找字符串中任何位置的模式。您可能需要match,使用一个锚定模式(将^放在开始,$放在末尾,以强制整个字符串匹配)。
pattern = re.compile('^[a-zA-Z \.]+$')https://stackoverflow.com/questions/59617952
复制相似问题