2013-05-27 37 views
0

在程序的某個位置,我要求它取用戶的文本輸入並根據它的逗號分隔文本,然後我再次將它寫入一個txt文件。這個想法是有一個包含所有逗號分隔信息的列表。.split(「,」)分隔字符串的每個字符

的問題是,很顯然,當我",".join它,它用逗號每一個字符分隔,所以如果我有字符串info1,info2它分離,得到info1 | info2,但隨後,在加入它時,再次它像結束i,n,f,o,1,,,i,n,f,o,2,這是非常不舒服的,因爲它從txt文件中取回文本以便在程序中稍後顯示給用戶。任何人都可以幫助我嗎?

 categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'a') 
     categories.write(BookCategory + '\n') 
     categories.close() 
     categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'r') 
     categoryList = categories.readlines() 
     categories.close() 

      for category in BookCategory.split(','): 
       for readCategory in lastReadCategoriesList: 
        if readCategory.split(',')[0] == category.strip(): 
         count = int(readCategory.split(',')[1]) 
         count += 1 
         i = lastReadCategoriesList.index(readCategory) 
         lastReadCategoriesList[i] = category.strip() + "," + str(count).strip() 
         isThere = True 
       if not isThere: 
        lastReadCategoriesList.append(category.strip() + ",1") 
       isThere = False 

      lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w') 
      for category in lastReadCategoriesList: 
       if category.split(',')[0] != "" and category != "": 
        lastReadCategories.write(category + '\n') 
      lastReadCategories.close() 

     global finalList 

     finalList.append({"Title":BookTitle + '\n', "Author":AuthorName + '\n', "Borrowed":IsBorrowed + '\n', "Read":readList[len(readList)-1], "BeingRead":readingList[len(readingList)-1], "Category":BookCategory + '\n', "Collection":BookCollection + '\n', "Comments":BookComments + '\n'}) 

     finalList = sorted(finalList, key=itemgetter('Title')) 

     for i in range(len(finalList)): 
      categoryList[i] = finalList[i]["Category"] 
      toAppend = (str(i + 1) + ".").ljust(7) + finalList[i]['Title'].strip() 
      s.append(toAppend) 

     categories = open('c:/digitalLibrary/' + connectedUser + '/category.txt', 'w') 
     for i in range(len(categoryList)): 
      categories.write(",".join(categoryList[i])) 
     categories.close() 
+0

分享你的代碼,所以我們可以把您有 – Duniyadnd

+0

肯定錯誤,對不起,忘了這樣做 – AugustoQ

+0

OK ,有代碼的重要部分,如果你需要任何其他的東西只是讓我知道。 – AugustoQ

回答

8

你應該通過''.join()列表,你傳遞一個字符串代替。

字符串是序列太多,所以''.join()對待每一個字符作爲一個單獨的元素,而不是:

>>> ','.join('Hello world') 
'H,e,l,l,o, ,w,o,r,l,d' 
>>> ','.join(['Hello', 'world']) 
'Hello,world'