从另一个文件获取特定文本(python)

2024-04-16 15:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以下模式的文件:

"abcd.asxs." "alphabets"
"wedf.345.po&%12." "numbers"
"xyhd.iu*u." "characters"
"megaten4.koryaku-memo.xyz." "alphabets"
"adwdbk.uyequ." "alphabets"
"233432.2321." "numbers"
"tytqyw.sdfhgwq." "alphabets"

我想要这样的东西:

string[0]=abcd.asxs
string[1]=megaten4.koryaku-memo.xyz
string[2]=tytqyw.sdfhgwq
and so on....

我写的代码是:

 #!/usr/bin/python

 import re

 important = []
 needed_categories = ["alphabets"]

 with open('file.txt') as fp:
        rec=fp.readlines()

 for line in rec:
        for category in needed_categories:
                if category in line:
                        important.append(line)
                        break
 print("\n".join(important))

我得到的输出:

““abcd.asxs文件.“字母表”

“megaten4.koryaku-备忘录.xy.“字母表”

““tytqyw.sdfhgwq公司.“字母表”


Tags: 文件instringline字母表abcdmemonumbers
2条回答

代码点数:

  • 可以直接使用文件句柄逐行迭代。不需要在列表中使用fp.readlines()保存文件数据,然后进行迭代。你知道吗
  • 一旦找到所需的类别,您就可以直接附加完整的行。这就是为什么你得到了错误的输出。您只需要拆分行并保存第一个元素。你知道吗
  • 我不明白你为什么用break。你知道吗

工作代码:

important = []
needed_categories = ["alphabets"]

with open('a.txt') as fp:
    for line in fp:
        temp = []
        for category in needed_categories:
            if category in line:
                temp = line.split()
                important.append(temp[0].replace('"','').strip("."))
print((important)

输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
['abcd.asxs', 'megaten4.koryaku-memo.xyz', 'adwdbk.uyequ', 'tytqyw.sdfhgwq']

C:\Users\dinesh_pundkar\Desktop>

important.append(line)更改为:

if line.strip().endswith('"alphabets"'): important.append(line.split(' ')[0].strip('"').strip('''))

相关问题 更多 >