簡體   English   中英

Python:如何獲取帶有名稱列表、兩列格式的導入文本文件,並將它們放入按字母順序排序的 Python 中?

[英]Python: How do I take an imported text file with a list of names, two column format, and put them in python sorted alphabetically?

這是我到目前為止所擁有的,並且在使用 sort()、sorted() 時它會給我錯誤。 我必須導入名稱並打印它們。 對名稱進行排序並再次打印。

文本文件格式為兩列,來自記事本

Riggs, Jerry
Stone, Ruby
Wood, Holly
Dover, Ilene
Funt, Ella
Storm, Wayne
Lowe, Lyle
Free, Bjorn
Caine, Candy
Carr, Rex
Downs, Mark
Twain, Lionel
Thorn, Rose
Shore, Rocky
Bush, Rose
Waters, Muddy
Graves, Doug
Stone, Roxanne
Rivers, Wade
Banks, Rob
Carr, Rusty
Trout, Brooke
Carr, Rhoda
Apple, Adam
Ponds, Lily
Burns, Forest
Dover, Ben
Sales, Clarence
Nichol, Penny
Beech, Sandy

我只是無法按字母順序對名稱或如何進行排序。 期望的結果是它將打印與文本文件相同的樣式,分兩列。

def main():
    infile = open('names.txt','r')
    str = infile.read()
    print(str)
    name = str

    for name in str:
        ch = 'X'
        print(name)

    #for line in str:
        #str = line.readlines()
        #print(line)

    name = input('Who are you looking for? (case sensitive):') 
    if name in str:
        print(name,'was found in the list')
    else:
        print(name,'was not found in the list')
    infile.close()

main()

試試下面的代碼,希望這會有所幫助:

def main():
  with open('data.txt') as fp:
    data = fp.read()

  list_str = sorted(data.split("\n"))
  print("\n".join(list_str))

  name = input('Who are you looking for? (case sensitive:') 
  if name in list_str:
      print(name,'was found in the list')
  else:
      print(name,'was not found in the list')

main()

輸出:

Apple, Adam
Banks, Rob
Beech, Sandy
Burns, Forest
Bush, Rose
Caine, Candy
Carr, Rex
Carr, Rhoda
Carr, RustyDover, Ben
Dover, Ilene
Downs, Mark
Free, Bjorn
Funt, Ella
Graves, Doug
Lowe, Lyle
Nichol, Penny
Ponds, Lily
Riggs, Jerry
Rivers, Wade
Sales, Clarence
Shore, Rocky
Stone, Roxanne
Stone, Ruby
Storm, Wayne
Thorn, Rose
Trout, Brooke
Twain, Lionel
Waters, Muddy
Wood, Holly

Who are you looking for? (case sensitive: Apple, Adam
Apple, Adam was found in the list

正如你所說,你已經在一個字符串中獲得了文件的內容。 相反,您需要一個列表,為此,您可以執行以下任一操作:

infile = open('names.txt','r')
names = infile.read().split('\n')

或者更好,

names = infile.readlines()

之后,排序很簡單:

sorted_names = sorted(names, key=lambda x: x.split(', ')[1]) #if you want to sort on first names
sorted_names = sorted(names, key=lambda x: x.split(', ')[0]) #if you want to sort on last names

暫無
暫無

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

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