我需要在记录中找到(F)irstname(L)astname并更改该记录的(B)irthday。当输入是“亚当”“斯密”时,我得到了输入,就像在“亚当·斯密”和“亚当·斯密”中找到的一样,而且两个生日都变了。我曾尝试使用索引来分离姓氏,并将其与“L”的值进行比较,但它从未注册为true。你知道吗
if re.search(F, recordLine):
lastName = recordLine[start+16:start+32]
if L == lastName:
recordLine = record[start:start + recordLength - 8]+ B
为了解决这个问题,我尝试用下面代码中的if语句替换这段代码,但它永远不会返回True。你知道吗
recordLength = 40
start = 0
recordList = []
file1 = open(P, 'r')
record = file1.read()
file1.close()
file1 = open(P, 'w')
while( (len(record) - start) >= recordLength):
recordLine = record[start:start + recordLength]
recordList.append(recordLine)
if re.search(F, recordLine) and re.search(L, recordLine):
recordLine = record[start:start + recordLength - 8]+ B
file1.write(recordLine)
start+= recordLength
file1.close()
Your output:
Adam Smith 11111900*
Theodore Anderson 03201990
Monty Biscuit-Barrel 10181980
Adam Smithers 11111900*
Ruthy Anderson 06062010
Expected output:
Adam Smith 11111900*
Theodore Anderson 03201990
Monty Biscuit-Barrel 10181980
Adam Smithers 10101960
Ruthy Anderson 06062010
指示的(B)irtdate是更改的日期。我们正在使用的程序似乎用不同的变量来运行代码,以确保它正常工作,所以很难确切地知道它是什么。但我的问题是F=Adam和L=Smith
你需要正则表达式。你知道吗
您已经在使用
re
进行搜索,所以您已经完成了一半。你知道吗基本上,正则表达式允许您搜索字母的模式,而不是字母本身-在您的情况下,您希望搜索与“Smith”匹配的短语,然后停止,不再包含字母。你知道吗
在正则表达式中,
$
是表示“不再有字符”的字符—它匹配字符串的结尾Smith$”将匹配单词“Smith”,但不匹配“Smithers”或“Smithson”。你知道吗看看re documentation和regexr。你知道吗
您有名字和姓氏,因此可以创建这样的模式
r'Adam\s+Smith\s+'
,但是假设名字可以有多个单词。你知道吗为了处理这个问题,我们知道名字的
length
是16
,姓氏是16
,生日是8
,我们可以通过切片或正则表达式提取这些信息:相关问题 更多 >
编程相关推荐