如果不匹配包含相同字符的字段,如何在固定长度记录中查找和更改条目?史密斯一词在史密斯一家是真的

2024-09-28 03:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在记录中找到(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


Tags: 代码researchif记录recordstartfile1
2条回答

你需要正则表达式。你知道吗

您已经在使用re进行搜索,所以您已经完成了一半。你知道吗

基本上,正则表达式允许您搜索字母的模式,而不是字母本身-在您的情况下,您希望搜索与“Smith”匹配的短语,然后停止,不再包含字母。你知道吗

在正则表达式中,$是表示“不再有字符”的字符—它匹配字符串的结尾Smith$”将匹配单词“Smith”,但不匹配“Smithers”或“Smithson”。你知道吗

看看re documentationregexr。你知道吗

您有名字和姓氏,因此可以创建这样的模式r'Adam\s+Smith\s+',但是假设名字可以有多个单词。你知道吗

为了处理这个问题,我们知道名字的length16,姓氏是16,生日是8,我们可以通过切片或正则表达式提取这些信息:

import re

FIRST_NAME = 'Adam'
LAST_NAME = 'Smith'
P = 'data.txt'
B = '11111900'

# if every record is in one line do this is better
with open(P, 'r') as readable_file1:
    records = readable_file1.readlines()


with open(P, 'w') as writable_file1:
    for record in records:
        # you can do by slicing like you did
        info = re.search('(.{16})(.{16})(.{8})', record)
        if info:
            first_name, last_name, birthday = info.groups()
            if first_name.strip() == FIRST_NAME and last_name.strip() == LAST_NAME:
                print('Record to update: ', record)
                record = record[:32] + B + '\n'
        writable_file1.write(record)

相关问题 更多 >

    热门问题