【问题标题】:Python. how do i do split() from txt file?Python。我如何从 txt 文件中拆分()?
【发布时间】:2020-08-27 21:48:41
【问题描述】:
 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']

将不胜感激。谢谢

【问题讨论】:

  • 欢迎来到 SO!请说明您的问题、您尝试过的内容以及您的输出与预期输出有何不同。现在我们只有一些输入、预期输出和五行代码,甚至不是有效的 python。
  • 你需要在空间上分割line。然后,对于结果数组中的每个单词,检查它是否在lst. 中,如果没有,添加它。

标签: python list


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    words = set()
    with open('path/to/romeo.txt') as file:
        for line in file.readlines():
            words.update(set(line.split()))
    
    words = sorted(words)
    

    【讨论】:

      【解决方案3】:

      以下应该可以工作:

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

      【讨论】:

        【解决方案4】:

        在 python 中使用sets 比在您的示例中使用列表更好。

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-08
          • 1970-01-01
          • 2018-04-05
          • 2018-10-25
          相关资源
          最近更新 更多