如果不在.yaml fi中,则在.txt文件中写一整行

2024-10-16 17:15:58 发布

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

我正在试着写一篇文章(下载.txt)来自打开.txt不存在相同的“id”,并且在异常中没有(idexception,classexception)。我已经写了“身份证”不重复了。在

我的问题是如何添加条件'classexception',我试过了,但这是不可能的。你知道我要用的词典/条件句吗?在

c = open('open.txt','r') #structure: name:xxx; id:xxxx; class:xxxx; name:xxx; id:xxxx;class:xxxx etc
t=c.read()
d=open('download.txt','a')

allLines = t.split("\n")    
lines = {}
class=[s[10:-1] for s in t.split() if s.startswith("class")]  
for line in allLines:        
    idPos = line.find("id:")     
    colPos = line.find(";",idPos)       
    if idPos > -1: 
       id = line[idPos+4: colPos if colPos > -1 else None] 
    if id not in idexception:   
          lines.setdefault(id,line) 

 for l in lines:
  d.write(lines[l]+'\n')
c.close()
d.close()

Tags: nameintxtidforiflineopen
1条回答
网友
1楼 · 发布于 2024-10-16 17:15:58

一般来说,你很不清楚,但如果我理解正确,我的方法是处理你的问题,里面有很多评论:

import re

id_exceptions = ['id_ex_1', 'id_ex_2']
class_exceptions = ['class_ex_1', 'class_ex_2']

# Values to be written to dowload.txt file
# Since id's needs to be unique, structure of this dict should be like this:
# {[single key as value of an id]: {name: xxx, class: xxx}}
unique_values = dict()  

# All files should be opened using 'with' statement
with open('open.txt') as source:
    # Read whole file into one single long string
    all_lines = source.read().replace('\n', '')
    # Prepare regular expression for geting values from: name, id and class as a dict
    # Read https://regex101.com/r/Kby3fY/1 for extra explanation what does it do
    reg_exp = re.compile('name:(?<name>[a-zA-Z0-9_-]*);\sid:(?<id>[a-zA-Z0-9_-]*);\sclass:(?<class>[a-zA-Z0-9_-]*);')
    # Read single long string and match to above regular expression
    for match in reg_exp.finditer(all_lines):
        # This will produce a single dict {'name': xxx, 'id': xxx, 'class': xxx}
        single_line = match.groupdict()
        # Now we will check againt all conditions at once and
        # if they are not True we will add values as an unique id
        if single_line['id'] not in unique_values or  # Check if not present already
        single_line['id'] not in id_exceptions or  # Check is not in id exceptions
        single_line['class'] not in class_exceptions:  # Check is not in class exceptions
            # Add unique id values
            unique_values[single_line['id']] = {'name': single_line['name'],
                                                'class': single_line['class']}
# Now we just need to write it to download.txt file
with open('download.txt', 'w') as destintion:
    for key, value in all_lines.items():  # In Python 2.x use all_lines.iteritems()
        line = "id:{}; name:{}; class:{}".format(key, value['name'], value['class'])

相关问题 更多 >