簡體   English   中英

需要從文本文件python中整理出字符串

[英]need to sort out strings from a text file, python

我已經編寫了一個程序,該程序可以查看社會保險號並將其寫入文本文件,或者將它們寫入程序中(如果該號碼有效)。 或如果數字太長,則帶有注釋,例如數字太長。

現在,我希望能夠分別“要求他們”,但是我不知道如何在文本文件中將有效數字與無效數字分開。

def showALLnumbers():
    print ("all numbers:")
    textfile = open("textfile.txt", "r")
    data = textfile.read()
    print (data)
    textfile.close

這就是我呼吁所有人的方式,但是如何僅獲得帶有以下注釋的注釋,以及如何獲得沒有此類注釋的注釋?

if socialsecuritynumber.isdigit()== False:
    print (number, "\t", "not only digits")
    textfile.write("\n" + socialsecuritynumber + "\t" + "not only digits" )
    return False

抱歉,文本內容凌亂,不勝感激!

編輯-這就是它在文本文件中的外觀

  1. 1992051155700數字太多
  2. 9205115570
  3. 92051155700
  4. 199205115570格式不正確,多數民眾贊成在文本文件的外觀,但沒有1,2,3,4

為了將來參考,您確實應該將代碼保存為更好的格式-CSV是一種很好的格式,Python對此提供了直觀的支持。 能夠在Excel中加載和更改內容非常重要!

無論如何,讓我們使用您現在所擁有的。 我們要做的是遍歷文件的每一行,並通過用空格字符分隔行來檢查是否有注釋。 CSV基本上以相同的方式工作,不同之處在於CSV強制要求分割線的方式,以使其結構化,並且不會在意想不到的地方意外分割內容。 請注意,如果我們按空格分割,如果我們可能有一個類似“ 1234 5678”的條目,它將無法正確解析!

進入代碼。 從你的問題,這聽起來像你不希望有任何保存的數據結構,如果你的文件變得非常大,其可能會遇到性能問題-我認為我們無處如此規模接近,所以這是很好。

def showGoodNumbers():
    print ("all good numbers:")
    textfile = open("textfile.txt", "r")
    for line in textfile.readlines():
        split_line = line.split(' ')
        if len(split_line) == 1:
            print(split_line) # this will print as a tuple
    textfile.close

def showBadNumbers():
    print ("all bad numbers:")
    textfile = open("textfile.txt", "r")
    for line in textfile.readlines():
        split_line = line.split(' ')
        if len(split_line) > 1:
            print(split_line) # this will print as a tuple
    textfile.close

您也可以將它們組合成一個調用,以使用getter創建兩個列表:

good = []
bad = []

def getNumbers():
    textfile = open("textfile.txt", "r")
    for line in textfile.readlines():
        split_line = line.split(' ')
        if len(split_line) > 1:
            good.append(line)
        else:
            bad.append(line)
    textfile.close

def getBadNumbers():
    print("Getting bad numbers")
    print("\n".join(bad))

def getGoodNumbers():
    print("Getting good numbers")
    print("\n".join(good))

我不確定您的問題到底是什么。 您是說您已經預先批注了一批社會保險號碼,並且需要選擇帶有注釋的號碼嗎? 如果是這樣,則如下所示:

comment_list = []
normal_list = []
for line in file:
    if len(line) > 9:
        comment_list.append(line)
else:
    normal_list.append(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM