蟒蛇。我如何从txt文件中拆分()?

时间:2020-08-27 12:32:49

标签: python list

 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()进行操作。否则,它将显示错误。因为这是来自coursera.com的作业

fname = 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 个答案:

答案 0 :(得分:1)

要阅读文本文件,必须先打开它:

include(FetchContent)
FetchContent_Declare(
  opencv
  GIT_REPOSITORY https://github.com/opencv/opencv.git
  GIT_TAG 4.4.0)

FetchContent_GetProperties(opencv)
if(NOT opencv_POPULATED)
  FetchContent_Populate(opencv)
  add_subdirectory(${opencv_SOURCE_DIR} ${opencv_BINARY_DIR})
endif()

使用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中。)

答案 1 :(得分:1)

words = set()
with open('path/to/romeo.txt') as file:
    for line in file.readlines():
        words.update(set(line.split()))

words = sorted(words)

答案 2 :(得分:1)

以下应该有效:

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))

答案 3 :(得分:0)

在python中使用set比在示例中列出要好。

集合是没有重复成员的可迭代对象。

# 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))


相关问题