2016-08-11 58 views
-1

昨天我的应用程序的这一部分工作,我似乎无法找出为什么它现在不工作。有条件地重新格式化字符串时出错

这里是它应该做的:

输入:10th ave 501

输出:501 10th ave

的代码块应该寻找所谓patterns在列表中的目标词之一,而如果后面有一个len <= 4,将它移动到字符串的前面。 patterns包含文字如ave, street, road, place

这里是我的代码:

address = address.split(' ') 
for pattern in patterns: 
    try: 
     if address[0].isdigit(): 
      continue 
     location = address.index(pattern) + 1 
     number_location = address[location] 
     if 'th' in address[location + 1] or 'floor' in address[location + 1] or '#' in address[location]: 
      continue 
    except (ValueError, IndexError): 
     continue 
    if number_location.isdigit() and len(number_location) <= 4: 
     address = [number_location] + address[:location] + address[location+1:] 
     break 
address = ' '.join(address) 

print address 

目前输出仅仅是完全相同的为我输入。即10th ave 501正在返回10th ave 501。我觉得这是相当明显的,我看了一眼。

+1

为了让您更容易理解您的代码,只需将一种类型的数据放入一个单一的变量名称。例如,你将'address'作为一个字符串并且也作为一个列表('address = address.split('')')。 – dsh

+0

501的长度不能小于或等于4? – Harrison

+0

@哈里森如果这不是家庭作业,你想解决街道正常化的问题,也许这个[包](https://github.com/openvenues/pypostal)可以帮你解决 – BPL

回答

0

'10th'.isdigit()False因为:

返回true,如果字符串中的所有字符是数字(source

如果你愿意,你可以检查的第一个字符:

if number_location[0].isdigit() and len(number_location) <= 4: 
+0

有道理。这应该处理正确的地址也通过应用程序的情况,例如'501 10th ave'。我能做些什么来处理所有情况?我的意思是如果一个地址已经以#开头,那么它会通过,但其他任何东西都会被测试。 – Harrison

+0

我不确定所有的情况。你需要自己定义所有选项,然后解决。 –