gpt4 book ai didi

python - 我无法理解奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:12 28 4
gpt4 key购买 nike

有人可以向我解释一下,为什么当我删除包含“#重复”的行时会得到不同的结果?

import re    

def nysiis(term: str) -> str:
"""
returns New York State Identification and Intelligence Algorithm (NYSIIS) code for given term
"""

if not len(term):
return ''
else:
term = term.upper()

table = {
r'\W+': '', # remove whitespace and non-word characters

r'^MAC': 'MCC',
r'^KN': 'NN',
r'K': 'C',
r'PH|PF': 'FF',
r'SCH': 'SSS',

r'(EE|IE)$': 'Y',
r'(DT|ND|NT|RD|RT)$': 'D',

# From now on first letter must no longer change.
r'(?<!^)EV': 'AF',
r'(?<!^)[AEIOU]': 'A',
r'(?<!^)Q': 'G',
r'(?<!^)Z': 'S',
r'(?<!^)(?:M|KN)': 'N',

r'(?<!^)([^AEIOUY])H': r'\1',
r'(?<!^)(.)H[^AEIOUY]': r'\1',
r'(?<!^)([AEIOUY])W': r'\1',

r'AY$': r'Y',
r'S$': r'',

r'(\w)\1+': r'\1', # original
r'A+$': r'' # original
}

for k, v in table.items():
term = re.sub(k, v, term)

table = { # duplicate
r'(\w)\1+': r'\1', # duplicate
r'A+$': r'' # duplicate
} # duplicate

for k, v in table.items(): # duplicate
term = re.sub(k, v, term) # duplicate

return term

if __name__ == '__main__':
names = [
'Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',
'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',
'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',
'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',
"O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins',
'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',
'knight', 'mitchell', "o'daniel",
]

for name in names:
print('%15s: %s' % (name, nysiis(name)))

最佳答案

您不想使用字典进行替换:迭代的顺序与您列出它们的顺序不同。如果您将字典更改为对列表,那么它会按您的预期工作.

table = [
(r'\W+', ''),
#...
]

for k, v in table:
...

关于python - 我无法理解奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31293803/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com