【问题标题】:How to skip the words not in the dictionary如何跳过字典中没有的单词
【发布时间】:2023-03-19 11:00:01
【问题描述】:

我有一个文件作为字典词:

water=45 
melon=8 
apple=35 
pineapple=67 
I=43 
to=90 
eat=12 
tastes=100 
sweet=21 
it=80 
watermelon=98 
want=70
juice=88

我还有另一个文件,其中包含以下文本:

I want to eat banana and watermelon 
I want drink juice purple and pineapple

我要输出:

43, 70, 90, 12, 98
43, 70, 88, 67

字典中不存在的每个单词都在skip中。

这是我目前所拥有的:

import re
f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r')
val_dict = {}
for line in f:
     k, v = line.strip().split('=')
     val_dict[k.strip()] = v.strip()
f.close()


h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r')
str_list = []
for line in h:
     str_list.append(str(line).strip())



tmp_str = ''
for val in str_list:
    tmp_str = val 
    for k in val_dict.keys():
            if k in val:
                replace_str = str(val_dict[k]).strip() + ","
                tmp_str= re.sub(r'\b{0}\b'.format(k),replace_str,tmp_str,flags=re.IGNORECASE)

    tmp_str = tmp_str.strip(",")
    print val, " = ", tmp_str
    tmp_str = ''

输出:

43, 70, 90, 12, banana and 98
43, 70, drink 88, purple and 67

【问题讨论】:

    标签: python python-2.7 python-3.x dictionary


    【解决方案1】:

    您可以使用dict.get,如果您找不到密钥,则可以使用默认值。

    >>> d = {'a': 1, 'b': 2}
    >>> d['c']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'c'
    
    >>> d.get('c', 'fallback value')
    'fallback value'
    

    这会让你做类似的事情:

    nums = [dict.get(val, '') for val in str_list]
    # [43, 70, 90, 12, '', '', 98]
    

    然后用filter删除空字符串

    nums = filter(None, nums)
    # with `None` as the first argument, this removes all elements that eval to False
    

    然后映射到字符串并用逗号连接

    print(", ".join(map(str, nums)))
    

    【讨论】:

    • 我有错误:TypeError:描述符'get'需要一个'dict'对象但收到了一个'str',这不是python的默认字典,我在文本文件中手动制作了一个字典。
    • @RiskaNanda 我的代码假定您已经将文本文件处理成字典,就像您在自己的代码中所做的那样。如有必要,我可以提供一个完整的示例。
    • 我仍然有点困惑如何应用它。你能举出一个完整的例子吗?
    • 我收到一个错误:TypeError: filter expected 2 arguments, got 1
    【解决方案2】:

    首先,我们可以使用巧妙的dict 理解将您的“字典文件”解析为实际的 Python 字典。

    In [1]: dict_file = """water=45 
       ...: melon=8 
       ...: apple=35 
       ...: pineapple=67 
       ...: I=43 
       ...: to=90 
       ...: eat=12 
       ...: tastes=100 
       ...: sweet=21 
       ...: it=80 
       ...: watermelon=98 
       ...: want=70
       ...: juice=88"""
    
    In [2]: conversion = {k: int(v) for line in dict_file.split('\n') for (k,v) in (line.split('='),)}
    
    In [3]: conversion
    Out[3]: 
    {'I': 43,
     'apple': 35,
     'eat': 12,
     'it': 80,
     'juice': 88,
     'melon': 8,
     'pineapple': 67,
     'sweet': 21,
     'tastes': 100,
     'to': 90,
     'want': 70,
     'water': 45,
     'watermelon': 98}
    

    然后我们将短语设置为一个变量。

    In [4]: text = "I want to eat banana and watermelon"
    

    我们可以使用str.split将单个字符串变成单词列表。

    In [5]: text.split()
    Out[5]: ['I', 'want', 'to', 'eat', 'banana', 'and', 'watermelon']
    

    要检查每个单词是否在conversion 字典中,我们可以简单地使用in 关键字来检查字典键。

    In [6]: "banana" in conversion
    Out[6]: False
    
    In [7]: "watermelon" in conversion
    Out[7]: True
    

    我们可以在列表推导中实现这一点,以仅过滤我们的转换字典知道如何转换为数字的单词。我们还可以查找值conversion[word],我们知道它存在,因为我们已经确认理解只查看转换中的值dict

    In [9]: [str(conversion[word]) for word in text.split() if word in conversion]
    Out[9]: ['43', '70', '90', '12', '98']
    

    最后,我们可以使用str.join 将这个列表重新组合成一个字符串。 (方括号被移除,这使得表达式成为 generator 推导式,而不是列表推导式,但无论哪种方式都可以。)

    In [10]: ', '.join(str(conversion[word]) for word in text.split() if word in conversion)
    Out[10]: '43, 70, 90, 12, 98'
    

    成功!您可以通过简单的for 循环将此方法应用于文件中的任何短语,以获得所需的结果。

    这里不需要太多正则表达式; Python 的字符串处理功能非常强大。 :)

    【讨论】:

    • 我试过运行代码,但是输出没有在执行...,这是他的代码link
    • @RiskaNanda 你复制了 IPython 生成的...:;如果您删除它们,它会起作用。 :)
    • 我已经删除了,结果还是一样。link
    • @RiskaNanda 您在每个项目之前留下了空格(12 个空格) - 所有项目都应与第一列对齐,事先没有空格。
    • 我得到 ValueError: too many values to unpack at line conversion = {k: int(v) for line in dict_file.split('\n') for (k,v) in (line.split('='),)}
    【解决方案3】:

    您可以使用list comprehension 执行类似的操作以获得所需的输出:

    我假设您的字典文件名为 file1,而您的第二个文件名为 file2

    data1 = [k.rstrip().split("=") for k in open("file1", 'r')]
    data2 = [k.rstrip().split() for k in open("file2", 'r')]
    
    for k in data2:
        for j in k:
            for m in data1:
                if j == m[0]:
                    print(m[1], end = ' ')
        print()
    

    输出:

    43 70 90 12 98 
    43 70 88 67
    

    【讨论】:

    • 我想在file2中输出合适的句子。
    • 我已经更新了我的答案。你可以得到完全期望的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2012-07-08
    相关资源
    最近更新 更多