项目验证和设置格式

2024-10-05 14:22:13 发布

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

我将解释我的代码的行为

  1. 输入文件名和项目名。

  2. 它将显示项目的名称和列表行中的数量。

第一个问题:实际上,我想让它显示列表中的第二项,并告诉它它是一个重复项。现在,如果我删除list(set(),我将在同一个字符串中分别得到两个香蕉输出。你知道吗

我正在导入的.txt文件的示例。你知道吗

bananes: 18
pommes: 23
bananes: 13

我正在导入的.txt文件的示例。你知道吗

pommes : 54
: 18
banane:

oranges : 30

输入示例:

item.py data10.txt bananes

所需输出示例:

La ligne banane : 13 est un doublon.

我得到的输出:

La ligne ['1', 's', ' ', 'e', ',', "'", '8', 'n', ':', 'b', '2', 'a'] est un doublon.

第二个问题:如果我写的不是列表中的单词,这个方法就可以了。但事实上,如果我写几个单词的第一个字母,它仍然会显示完整的行。你知道吗

输入示例:

item.py data10.txt pomm

所需输出示例:

pomm: 0

我得到的输出:

pomme: 30

这是我的代码,你可以知道我在做什么:

import sys

def ligne(texte):
    try:
        with open(texte) as ouvrir:
            lecture = ouvrir.readlines()
            words = [" : ".join([x.strip() for x in line.split(":")]) for line in lecture]
            words = [x for x in words if len(x) > 1]
            return words
    except IOError:
        print("Le fichier", texte, "n'existe pas.")
        sys.exit()

def recherche(essaie):
    while True:
        if len(essaie) > 3:
            print("Deux arguments sont attendus, le nom du fichier d'inventaire et l'item")
            sys.exit()
        elif len(essaie) < 3:
            print("Il faut préciser le nom du fichier et de l'item.")
            sys.exit()
        else:
            entree = essaie[1]
            item = essaie[2]
            choix = str(entree)
            texte = choix.strip("[']")
            resultat = [s for s in ligne(texte) if item in s]
            resultat2 = str(resultat)
            longueur = len(resultat)
            resultat3 = resultat2.strip("[']")
            resultat4 = list(set(resultat3))
            if item in str(ligne(texte)):
                if longueur > 1:
                    print("La ligne", resultat4, "est un doublon.")
                    sys.exit()
                else:
                    print(resultat3)
                    sys.exit()
            else:
                print(item, ": 0")
                sys.exit()

if __name__ == "__main__":
    recherche(sys.argv)

Tags: intxt示例列表forlenifsys
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:13

您可能需要考虑使用字典来解决这个问题,而不是使用字符串列表/字符串集。您可以将这些行作为键/值对读入,然后检查字典中是否已有键。如果是这样,它是一个复制并引发一个异常(如果您愿意,您可以用它代替打印的字符串和系统出口(0). 你知道吗

检查下面的示例代码。。。你知道吗

import sys

def ligne(texte, item):
    try:
        with open(texte) as ouvrir:
            words_dict = {} #Create new, empty dictionary
            lecture = ouvrir.readlines()
            for line in lecture: #For each line in .txt file
                line = line.strip('\n')
                key, number = line.split(':')[0], int(line.split(':')[1]) #Item is before ':', value is after
                if key not in words_dict.keys(): 
                    words_dict[key] = number #If that item isn't in the dictionary yet (this is the first occurence), add it
                elif key == item: #If the duplicate is the inputed item
                    raise Exception('La ligne {} est un doublon.'.format(line)) #If that item is already in the dictionary, raise an exception
            return words_dict #If there are no duplicates, the dictionary will be returned, if there are, it will return the error above
    except IOError:
        print("Le fichier", texte, "n'existe pas.")
        sys.exit()

def recherche(essaie):
    if len(essaie) > 3:
        print("Deux arguments sont attendus, le nom du fichier d'inventaire et l'item")
        sys.exit()
    elif len(essaie) < 3:
        print("Il faut preciser le nom du fichier et de l'item.")
        sys.exit()
    else:
        entree = essaie[1]
        item = essaie[2]

        choix = str(entree)
        texte = choix.strip("[']")
        resultat_dict = ligne(texte, item) #If this returns without raising an exception, there were no duplicates

        if item in resultat_dict.keys():
            print item, ": {}".format(resultat_dict[item]) #If the item was in the .txt file, print it and its value
        else:
            print item, ": 0" #If not, print with a value of zero

if __name__ == "__main__":
    recherche(sys.argv)

我试图留下评论来解释所有的变化,但是如果有什么不清楚的地方请告诉我。关键的变化是将文件读入字典,如果发现重复的文件,则引发异常,但我尽了最大努力保持原始代码的结构完整(尽管可能有更简单/更有效的方法)。recherche函数的最后一部分也通过这种方式变得简单得多,因为您知道,如果ligne返回时没有错误,那么就没有重复。你知道吗

相关问题 更多 >