2015-10-06 76 views
-3

对于可变电话号码,它要求输入整个电话号码;像这样:029 123456.然而,我只需要第一个区号。但也可以有这样的区号:01845 123456与区号的字符数量不同。我如何得到它,所以它只是将区号存储在变量中?在变量中搜索不同的字符串长度

这里的full CSV file的小样本:

PhoneCode,Area,Example,Latitude,Longitude 
113,Leeds,(0113) xxx xxxx,53.801279,-1.548567 
114,Sheffield,(0114) xxx xxxx,53.381129,-1.470085 
115,Nottingham,(0115) xxx xxxx,52.95477,-1.158086 
116,Leicester,(0116) xxx xxxx,52.636878,-1.139759 
117,Bristol,(0117) xxx xxxx,51.454513,-2.58791 
118,Reading,(0118) xxx xxxx,51.452884,-0.973906 
1200,Clitheroe,(01200) xxxxxx,53.871098,-2.393083 
1202,Bournemouth,(01202) xxxxxx,50.719164,-1.880769 
1204,Bolton,(01204) xxxxxx,53.584441,-2.428619 

,这里是我的代码至今:

phoneNumber = input("Enter your phone number (UK landline only):") 

file = open("phonecodes.csv","r") 

#Complete the code here 
for line in file: 
    data = line.split(",") 
    areaCode = data[0] 
    if phoneNumber == "0" + areaCode: 
    print data[1] 

file.close() 
+0

他们都在单独的列中,所以只需提取所需的列,使用csv模块 –

+0

两个注释:1)不要使用'file'作为变量名称;使用内建的变量名是一个坏主意。 2)'f = open(path)... f.close()'设计是一个反模式;更好地使用'与开放(路径)为f:...',这确保文件将始终关闭。 – alexwlchan

+0

@Padraic坎宁安谢谢,但这不是我问的。我问的是如何从phoneNumber中存储区号,而不是整个号码。所以,而不是存储029 123456,它只是存储029. – ConorYoungs

回答

0

要么得到用户的数量分别输入区号,然后或得到他们输入区号后跟一个空格,然后是数字和分割:

分开:

area = raw_input("Enter your area code: ") 
num = raw_input("Enter you phone number: ") 


import csv 

r = csv.reader(open("phonecodes.csv")) 
for ph_cde, ar_cde, ex, lat, lon in r: 
    if "0" + ph_cde == area: 
     ........ 

分裂:

area, num = raw_input("Enter your phone number (UK landline only) in format 

AREA NUM:").split() 


import csv 

r = csv.reader(open("phonecodes.csv")) 
for ph_cde, ar_cde, ex, lat, lon in r: 
    if "0" + ph_cde == area: 
     ......... 

你的数据是逗号分隔的如此csv模块将拆分为你列。我也使用raw_input作为你的打印语句,表明你使用的是python2而不是python3。

+0

感谢它的工作! – ConorYoungs

+0

没有问题,不客气。 –

相关问题