【问题标题】:Text file reading with dict in python在python中使用dict读取文本文件
【发布时间】:2019-09-20 05:05:03
【问题描述】:

从下面的文本文件中,将文本文件读入 python 程序并根据第一个字母对所有单词进行分组。以字典的形式表示组。其中凝视字母是“键”,所有以字母开头的单词都是“值”列表。

文本文件是:

Among other public buildings in a certain town, which for many reason it will be prudent to
refine from mentioning, and to which i will assign no fictitious name, there is one anciently
common to most towns, great or small.

【问题讨论】:

    标签: file-handling


    【解决方案1】:
    stream = open('file name', 'r')
    str = ''
    current = ' '
    while current != '':
        current = stream.read(50)
        str += current
    words = str.split(' ')
    dict = {}
    for w in words:
        if not w[0] in dict:
            dict[w[0]] = [w]
        else:
            dict[w[0]].append(w)
    

    字典是dict

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 2017-03-05
      • 2020-06-24
      • 2020-12-24
      • 1970-01-01
      • 2018-01-25
      • 2017-07-27
      • 2019-04-04
      • 2018-01-06
      相关资源
      最近更新 更多