首页 > 解决方案 > 在已分配给新值 Python 的文本中查找字符串列表

问题描述

我是 python 新手(我上周才开始学习)。我正在尝试编写一个执行以下操作的 python 脚本: 1- 插入一个文本,例如,“Hello world!” (或文件中的较大文本) 2- 创建所有英文字母表(或任何其他语言的字母表)的列表,其中每个字母都分配给一个新的字符串值,例如字母 k = 'cv-'。3-然后编写如下语句:如果文本中存在“h”,则打印出其分配的新字符串(从步骤 2 开始)。4-最终输出可能是这样的:cv-cvv-cv(对于文本中的每个单词)。

总而言之,我有“a”(文本)、“b”(字母列表)、“c”(每个字母的新值)、“d”(代码、if 语句或类似的东西), 'e',输出(类似于 cv-cvc-cv ..ete)。

运行 a,然后使用 d,通过 b 和 c,得到 e。

这是我的尝试(当然,没有运气)。我将不胜感激任何指导和帮助。

text = 'a test'
letters = ['a', 't', 'e', 's']

if letters in text:
 print (a_val, t_val, e_val, s_val)

标签: python

解决方案


    import string
    letters = list(string.ascii_lowercase)
    print(letters)
    output: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',         'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    text = "hope this will help"
    splited_text = text.split(" ")
    print(splited_text)
    output: ['hope', 'this', 'will', 'help']
    your_dictionary = {} # use dictionary, it suits your problem

    for i in range(len(splited_text)):
        your_dictionary[letters[i]] = splited_text[i]

    print(your_dictionary)
    output: {'d': 'help', 'c': 'will', 'a': 'hope', 'b': 'this'}

如果需要,您可以按键对字典进行排序。

    For k in your_dictionary.keys():
        If(your_dictionary[k] is in some_values):
            #do something

推荐阅读