如何从 flask 中的 txt(RIS) 文件中提取信息

How to extract information from a txt(RIS) file in flask

我的文件在文本编辑器中看起来如下所示:

Firstname  - phil
Lastname  - taylor
Birthdayyear  - 1956
Country  - england
END  -

我将文件存储在 python 变量 txtFile 中,当我使用 print(txtFile.read()) 打印文件时,它在控制台中看起来如下所示:

b'Firstname  - phil\r\nLastname  - taylor\r\nBirthdayyear  - 1956\r\nCountry  - england\r\nEND  - '

现在我需要获取名字、姓氏、生日年份和国家/地区,并将这些信息存储在变量中,以便以后可以访问这些信息。

例如,当我 print("His first name is " + firstName) 时,我会在控制台中得到 His first name is phil

txt 文件的架构并不总是相同的。 “Firstname”、“Lastname”、“Birthdayyear”和“Country”等名称始终相同,但顺序并不总是相同。因此,例如“Country”是第一行,“Firstname”是最后一行。

我还没有在 Whosebug 上发现和我一样的问题,所以也许有人可以帮我解决这个问题。

非常感谢

终于找到了解决问题的方法。我不知道这是否是最好的方法,但它对我有用:

首先,我浏览了 txt 文件的每一行,并将每一行添加到一个数组中。然后我 当行中有 " - " 时拆分数组的每一行。例如,将每一行从 ["Firstname - phil"] 拆分为 ["Firstname","phil"] 然后如果遍历数组的每一行并发出 if 请求,则可以访问该名称:如果该行的第一个元素等于"Firstname",将您的 firstName 变量设置为等于此行的第二个元素。我不知道这是否可以理解,但这是 python 代码中的样子...:-D

 txtFileToArray = []
 splittedTxtArray = []
 firstName=""

     #go through every line of the text file
     for line in txtFile:

          #put every line at the end of the array txtFileToArray and delete the "b" (binaray) at the beginning of every line
          txtFileToArray.append(line.decode('utf-8'))

    #then go through every line of the array and split every line when there is a "  - " and store the lines in a new array
     for line in txtFileToArray: 

          splittedTxtArray.append(element.split("  - "))

    #then check every line of the splitted array if there is a Firstname at the first position
    for linein splittedTxtArray:

          if(line[0] == "Firstname"):
             firstName= line[1]

我希望有一天这能对你有所帮助:-)