如何解析txt文件到json?

时间:2017-11-29 06:59:15

标签: ios json

我有一个包含8000多行信息的文本文件。我想将它解析为JSON,以便在iOS应用程序中使用它。因为解析那种txt文件大约需要35秒,这对用户体验不利。

文本文件如下:

TURKIYE;ADANA;ADANA;36,9914194;35,3308285;03:00:00
TURKIYE;ADANA;ALADAĞ;37,545348;35,394608;03:00:00
TURKIYE;ADANA;CEYHAN;37,028765;35,8124309;03:00:00
TURKIYE;ADANA;FEKE;37,814467;35,910391;03:00:00
TURKIYE;ADANA;İMAMOĞLU;37,2984443;35,6095474;03:00:00
TURKIYE;ADANA;KARAISALI;37,2758825;35,1268781;03:00:00
TURKIYE;ADANA;KARATAŞ;36,6649776;35,2587964;03:00:00

我只想要“TURKIYE”,“ADANA”,“ALADAĞ”,“Latitude”和“Longitude”部分,不需要最后一个“03:00:00”部分。

修改 忘了提一件事。文本文件中的某些行不包括第三列。例如;

AVUSTURYA;HORBRANZ;47,5557073;9,7525947;01:00:00
AVUSTURYA;HORN;48,66607;15,65716;01:00:00
AVUSTURYA;IMST;47,24013;10,73954;01:00:00
AVUSTURYA;IMSTERAU;47,21018;10,70901;01:00:00

我想解析它们,如果“如果第三列不存在则打印nil值。”

我的txt解析代码是:

let textFilePath = Bundle.main.path(forResource: "LatLongData", ofType: "txt")
let fileManager = FileManager.default

if fileManager.fileExists(atPath: textFilePath!) {

    do {
        let fullText = try String(contentsOfFile: textFilePath!, encoding: String.Encoding.utf8)
        let lines = fullText.components(separatedBy: "\n") as [String]
            for line in lines {

                let data = line.components(separatedBy: ";")
                let locationData = LocationData()

                if data.first == "TURKIYE" || data.first == "ABD" {
                    locationData.country = data[0]
                    locationData.city = data[1]
                    locationData.district = data[2]
                    locationData.latitude = data[3]
                    locationData.longitude = data[4]
                    locationData.compoundKey = "\(data[0])-\(data[1])-\(data[3])"
                 } else {
                    locationData.country = data[0]
                    locationData.city = data[1]
                    locationData.latitude = data[2]
                    locationData.longitude = data[3]
                    locationData.compoundKey = "\(data[0])-\(data[1])-\(data[3])"
                }
                locationData.writeToRealmDB()
            }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

如何将此文本转换为JSON以便在iOS应用中使用?

提前致谢。

1 个答案:

答案 0 :(得分:0)

import pandas as pd

with open('filename.txt', 'r') as f:
lines = f.readlines()
for line in lines:
    if line.count(';') == 4:
        index = line.index(';', 2)
        line = line[:index] + ';' + line[index:]
    with open('filename2.txt', 'a') as f2:
        f2.write(line)

df = pd.read_csv('filename2.txt', header=None, sep=';')
df = df.iloc[:, :-1]
df.columns = ['col1', 'col2', 'col3', 'Latitude', 'Longitude']
df.to_json('filename.json')

http://pandas.pydata.org/pandas-docs/stable/io.html