【问题标题】:Stripping from a text file从文本文件中剥离
【发布时间】:2018-04-03 10:53:00
【问题描述】:

如果我的文本文件包含以下内容:

['A', 'B', 'C', 21, '25', 'D', '6', '8', '100', 'A']['Q', 'W' , 'E', 21, '11', 'R', 'T', 3, 60, 'C']

我想将每个列表中的第一项收集到 python- 例如:A 和 Q。我该怎么做?

我可能想稍后收集第三个值,例如 C 和 E

在下面编辑: 我现在有以下代码:

def ADMIN():
        print("Welcome")
        ADMINoption = input("Do you want option A or B.\n").upper()
        if ADMINoption == 'A':
            import re
            file = open('Membership.txt').read()
            temp = [re.split("\W+", i)[1:-1] for i in re.findall("\[(.*?)\]", file)]
            list_of_members = [i[0] for i in temp]
            print("The following are the usernames of the Members:")
            #print (*list_of_members)      THE * removes [] from list display
            for a in list_of_members:
                print (a)
            ADMINchoice=input("Select the member details you wish to inspect\n").upper()

ADMIN()

它产生以下内容:

"Welcome Do you want option A or B. a 
The following are the usernames of our members: 
DON21 
BAR50 
Select the member details you wish to inspect"

我的文本文件包含: ['DON21', '唐纳德', '特朗普', 21, 'GYM', 'X', 'Easy', 5, 100, 'PO']['BAR50', 'BARACK', '奥巴马', 50, '游泳', 'K', '训练', 3, 60, 'L']

如何获得问题的答案以开始从列表中返回相关值? 例如,如果我选择“DON21”,它会返回: ['DON21','唐纳德','特朗普',21,'GYM','X','Easy',5, 100,'PO'] 甚至是列表的选择,例如“TRUMP”、21、“GYM” ??

【问题讨论】:

  • 您有没有尝试过或希望我们为您编写代码?
  • 欢迎来到 SO。不幸的是,这不是一个讨论论坛或代码编写服务。请花时间阅读How to Ask 及其包含的链接。您应该花一些时间通过the Tutorial 练习这些示例。它将向您介绍 Python 必须提供的工具,您甚至可能会开始获得解决问题的想法。
  • 谢谢'wwii',我还没有意识到要对你诚实。有时间我会看教程的

标签: python string text


【解决方案1】:

你可以试试这个:

d = [['A', 'B', 'C', 21, '25', 'D', '6', '8', '100', 'A'], ['Q', 'W', 'E', 21, '11', 'R', 'T', 3, 60, 'C']]
s = [i[0] for i in d]

输出:

['A', 'Q']

从文本文件中访问数据:

import re
data = open('filename.txt').read()
new_data = [re.split("\W+", i)[1:-1] for i in re.findall("\[(.*?)\]", data)]
final_data = [i[0] for i in new_data]

【讨论】:

  • 可以从 text.txt 中收集它吗?
  • 它说这个错误:“TypeError: list indices must be integers, not tuple”
  • @UKcodeNovice 如果此答案对您有帮助,请考虑接受。谢谢!
  • @UKcodeNovice 只需单击此问题左侧的复选标记框。谢谢!
  • @UKcodeNovice 它不会关闭线程,因为其他用户仍然可以发布答案。
猜你喜欢
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2011-06-04
  • 2011-06-18
  • 2017-04-04
  • 1970-01-01
相关资源
最近更新 更多