【发布时间】:2013-08-25 03:12:04
【问题描述】:
我正在使用正则表达式来清理名称列表,以便它们正常。假设这个列表是...
000000AAAAAARob Alsod ## Notice multiple 0's and A's?
AAAPerson Person ## Here, too
Jeff the awesome Guy ## Four words...
Jenna DEeath ## A name like this can exist.
GEOFFERY EVERDEEN ## All caps
shy guy ## All lowercase
Theone Normalperson ## Example name. This one is fine.
Guywith Whitespace ## Trailing or leading whitespace is a nono.
所以,如您所见,人们的姓名格式不正确,因此我需要一个程序来突出显示所有不需要的内容。这包括:
名称开头处的数字。
Any 大写后没有小写。即 AAAAAAAJosh
全部大写。
任何不以大写开头的东西。即乔希
尾随和前导空格。
我认为这就是我需要过滤掉的所有内容。最终产品应如下所示:
Rob Alsod ## No more 0's and A's.
Person Person ## No more leading A's (or other letters).
Jeff Guy ## No lowercase words in his name.
Jenna DEeath ## HASN'T removed the D in the middle.
## Name removed as it was all uppercase.
## Name removed as it was all lowercase.
Theone Normalperson ## Nothing changed.
Guywith Whitespace ## Removed whitespace.
编辑:很抱歉。这是我当前的代码:
# Enter your code for "Name Cleaning" here.
import re
namenum = []
num = 0
for sen in open('file.txt'):
namenum += [sen.split(',')]
namenum[num][0] = re.sub(r'\s[a-z]+', '', namenum[num][0])
namenum[num][0] = re.sub(r'^([0-9]*)', '', namenum[num][0])
namenum[num][0] = re.sub(r'^[A-Z]*?\s[A-Z]*?$', '', namenum[num][0])
namenum[num][0] = re.sub(r'[^a-zA-Z ][A-Z]*(?=[A-Z])', '', namenum[num][0])
namenum[num][0] = re.sub(r'\b[a-z]+\b', '', namenum[num][0])
namenum[num][0] = re.sub(r'^\s*', '', namenum[num][0])
namenum[num][0] = re.sub(r'\s*$', '', namenum[num][0])
if namenum[num][0] == '':
namenum[num][0] = 'Invalid Name'
num += 1
for i in range(len(namenum)):
namenum[i][1] = int(namenum[i][1].strip())
namenum = sorted(namenum, key=lambda item: (-item[1], item[0]))
for i in range(0, len(namenum)):
print(namenum[i][0]+','+str(namenum[i][1]))
它完成了一半的工作,但由于某种原因它错过了一些东西。
这是输出:
AAAAAARob Alsod
AAAPerson Person
Guywith Whitespace
Invalid Name
Invalid Name
Jeff Guy
Jenna DEeath
Theone Normalperson
我还尝试输入像 harry hamilton 这样的名称,它返回了应该删除的 harry。
【问题讨论】:
-
你实际上必须尝试一些东西。到目前为止,您的代码在哪里?我们不是免费的代码工厂。 -1,近距离投票
-
对不起。我已经编辑了 OP。
-
错过了什么?
-
只是出于好奇,您为什么需要这样做?名字很复杂。
-
我正在创建一个数据库。它包含我们系统中人员的姓名。不幸的是,名称是手动输入的,这导致一些人开玩笑并写
Robert le awesome Alsod而不是他们的正常名称。顺便说一句,@Michelle,它已被编辑。
标签: python regex python-3.x