Tab delimeter以逗号分隔符转移故障

时间:2015-08-08 16:45:40

标签: python string python-2.7 text-files

我有一个关于使用Python在for循环中从文本文件打印数据的问题。每当我尝试运行这个程序时,它说'#34;无法将字符串转换为浮点数:KAAA" (KAAA是元素[2]中的字符串元素)。我试图将带有制表符分隔符的文本文件中的数据传输到带逗号分隔符的文本文件。出于某种原因,如果我删除第三列字符串,这个程序工作正常,但是当我将其添加回来时却没有。有没有办法可以获得它所以所有三列都转移到一个文本文件中分开他们的逗号?以下是数据的示例行。 " 40.15869904 -89.33499908 KAAA。"

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor)
opener.addheaders = [('User-agent','mr_anderson')]


keywords = map(''.join, product(ascii_lowercase, repeat=3))
keywords = ["k"+a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]

start_time = time.time()

print("--- %s seconds ---" % (time.time() - start_time))

try:
    a = 1
    b = 1
    List=[""]
    data = np.loadtxt("airportcodelatlonidentonlyk.txt")
    text_file_latlonair = open("latlontext.txt","a")
    for element in data:
        lat = str(element[0])
        lon = str(element[1])
        ident = str(element[2])
        text_file_latlonair.write(str(lat)+','+str(lon)+','+str(ident))
    text_file = open("nws_contourcurrenttemp_datatwo.txt","a")
    for i in range (1,50):
        i=1
        i+=1
        a+=1
        b+=1
        keywargs = str(keywords[a]).upper()
        argument = 'http://w1.weather.gov/xml/current_obs/'+keywargs+'.rss'
        page = 'http://w1.weather.gov/xml/current_obs/KBED.rss'
        sourceCode = opener.open(page).read()
        #print(sourceCode)
        req = Request(argument)


        try:
            page_open = urlopen(req)
        except:
            None

        else:

            c=1
            c+=1
            sourceCode = opener.open(argument).read()
            KBEDforecastraw = re.findall(r'and\s\d{1,2}\s\w.*?',str(sourceCode))
            windraw = re.findall(r'at\s\d{1,2}\.\d{0,1}.*?',str(sourceCode))
            pressureraw = re.findall(r'The pressure is\s\d{1,4}\.\d{0,1}\s\w\w.*?',str(sourceCode))
            humidraw = re.findall(r'the humidity is\s\d{1,2}\%.*?',str(sourceCode))

            try:
                KBEDtemp = KBEDforecastraw[0]
                KBED = str(KBEDtemp).strip("[and F]")
                #text_file.write(KBEDtemp)

            except:
                None
            else:
                text_file.write(KBED+'\n')
                #print(KBED)
                #print(str(KBEDforecastraw)+' '+keywargs+str(windraw)+str(pressureraw)+str(humidraw))








except Exception, e:
    print(str(e))



print("--- %s seconds ---" % (time.time() - start_time))

1 个答案:

答案 0 :(得分:0)

从您使用的np变量中猜测numpy,假设传递到load的数据是浮点类型。看起来您的代码假定所有内容都是字符串,因此只需传入str数据类型。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html