如何在Python中删除重复的拨号代码?

2024-10-01 07:36:28 发布

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

我正在尝试标准化国际电话号码的数据框列。除了重复的拨号代码,我已经设法摆脱了一切

例如,一些德国号码的格式为“00 49 49 7 123 456 789”,即它们包含两个连续的拨号代码(49)。我想知道是否有一个简单的解决办法,摆脱重复,并留下号码为“00 49 7 123 456 789”

我尝试了一些regex和itertools.groupby解决方案,但是没有成功,因为不同拨号代码的差异会导致问题

谢谢你的帮助


Tags: 数据代码格式电话号码差异解决方案regex号码
1条回答
网友
1楼 · 发布于 2024-10-01 07:36:28

这是一个非常数据驱动的问题,因此根据您处理的实际数据,解决方案可能会有很大的变化。无论如何,这将实现您想要实现的目标:

number = "00 49 49 7 123 456 789"
# Split the number to a list of number parts
num_parts = number.split()
# Define the latest position to look for a dial number
dial_code_max_pos = 4
# Iterator of tuples in the form of (number_part, next_number_part)
first_parts_with_sibling = zip(
    num_parts[:dial_code_max_pos],
    num_parts[1:dial_code_max_pos]
)
# Re-build the start of the number but removing the parts 
# that have an identical right-sibling
first_parts_with_no_duplicates = [
    num[0] for num in first_parts_with_sibling
    if len(set(num)) > 1  # This is the actual filter
]
# Compose back the number
number = ' '.join(first_parts_with_no_duplicates + num_parts[dial_code_max_pos - 1:])

同样,这种规格化在生产中是非常危险的,由于算法没有覆盖所有可能的数据类型,最终可能会丢失有价值的数据

正如@Clèment在其评论中所说的,在应用任何转换之前,请确保对原始数字(即:长度)进行一些检查

相关问题 更多 >