亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python。如何從 txt 文件中執行 split() 操作?

Python。如何從 txt 文件中執行 split() 操作?

子衿沉夜 2023-06-27 14:04:47
 But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief從這個文件中我必須 8.4 打開文件 romeo.txt 并逐行讀取它。對于每一行,使用 split() 方法將該行拆分為單詞列表。該程序應該構建一個單詞列表。對于每行上的每個單詞,檢查該單詞是否已在列表中,如果沒有,則將其附加到列表中。程序完成后,按字母順序排序并打印結果單詞。您可以在http://www.py4e.com/code3/romeo.txt下載示例數據這是框架,所以我應該只遵循這個代碼,并使用append()、slpit()和sort()我應該使用它們?;蛘咴谄渌闆r下會顯示錯誤。因為這個作業來自 coursera.comfname = input("Enter file name: ")fh = open(fname)lst = list()for line in fh:print(line.rstrip())輸出應如下所示:      ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair',       'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through',       'what', 'window', 'with', 'yonder']將不勝感激。謝謝
查看完整描述

4 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

words = set()

with open('path/to/romeo.txt') as file:

    for line in file.readlines():

        words.update(set(line.split()))


words = sorted(words)


查看完整回答
反對 回復 2023-06-27
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

以下應該有效:


fname = input("Enter file name: ")


with open(fname, 'r') as file:

    data = file.read().replace('\n', '')


# Split by whitespace

arr = data.split(' ')


#Filter all empty elements and linebreaks

arr = [elem for elem in arr if elem != '' and elem != '\r\n']


# Only unique elements

my_list = list(set(arr))


# Print sorted array

print(sorted(arr))


查看完整回答
反對 回復 2023-06-27
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

要讀取文本文件,您必須先打開它:


with open('text.txt', 'r') as in_txt:

    values = in_txt

    l=[]

    for a in values:

        l.extend(a.split())

    print(l)

用于with確保您的文件已關閉。'r'用于只讀模式。 extend將從列表中添加元素,在本例中a添加到現有列表中l。


查看完整回答
反對 回復 2023-06-27
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

在 python 中使用sets 比示例中的 list 更好。


集合是沒有重復成員的可迭代對象。


# open, read and split words

myfile_words = open('romeo.txt').read().split()


# create a set to save words

list_of_words = set()


# for loop for each word in word list and it to our word list

for word in myfile_words:

    list_of_words.add(word)


# close file after use, otherwise it will stay in memory

myfile_words.close()


# create a sorted list of our words

list_of_words = sorted(list(list_of_words))


查看完整回答
反對 回復 2023-06-27
  • 4 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號