【问题标题】:Transform a python file into a list of letters将 python 文件转换为字母列表
【发布时间】:2021-06-29 18:15:27
【问题描述】:

我正在尝试将文件转换为 Python 中的列表,该列表将每个字母作为元素。文件“file_input.txt”应如下所示:

它 是 很棒

并且函数应该返回: ['i','t','i','s','g','r','e','a','t']

我尝试过这样做:

file1 = open('file_input.txt', "r")
list_of_lists = []
for l in a_file1:
    s_line = l.strip() 
    l_list = s_line.split()
    list_of_lists = l_list
file1.close()

但它不起作用,而且它应该不区分大小写,有人可以帮我吗?

【问题讨论】:

标签: python python-3.x string file arraylist


【解决方案1】:

我建议你做下面的事情

ans = []
with open("file_input.txt") as file:
    for line in file:
        ans.extend(list(line.replace(" ", "")))
print(ans) 

【讨论】:

    【解决方案2】:

    您可以使用上下文管理器打开文件,这样您就不会忘记关闭它:

    list_of_lists = []
    with open('file_input.txt') as file1:
        list_of_lists = [x.lower() for x in file1.read() if x != " " and x != "\n"]
    

    【讨论】:

      【解决方案3】:

      您可以使用list() 将字符串转换为字符列表,并使用str.replace() 删除字符串中的任何空格:

      file = open('file_input.txt', 'r')
      result = list(file.read().replace(' ',''))
      file.close()
      

      顺便说一句,如果您还想删除换行符,只需将 .replace('\n', '') 添加到结果行的末尾,在 ')' 之前

      另外,如果你想让它不区分大小写,只需将.lower() 添加到结果行的末尾,在')'之前

      【讨论】:

        猜你喜欢
        • 2019-03-25
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 1970-01-01
        • 2011-11-18
        相关资源
        最近更新 更多