【问题标题】:How to Find Words Not Containing Specific Letters?如何查找不包含特定字母的单词?
【发布时间】:2019-06-01 21:05:07
【问题描述】:

我正在尝试使用 regex 和我的文本文件编写代码。我的文件逐行包含这些单词:

nana
abab
nanac
eded

我的目的是:显示不包含作为子字符串字母给出的字母的单词。

例如,如果我的子字符串是"bn",我的输出应该只有eded。因为nanananac 包含“n”而abab 包含“b”。

我写了一个代码,但它只检查我的子字符串的第一个字母:

import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()

我该如何解决这个问题?

【问题讨论】:

  • 为什么是正则表达式?有更简单的方法可以检查两个字符串是否共享任何共同的字母。
  • 我正在研究正则表达式来理解它,所以我必须
  • 为什么是这一行?很难说它在做什么for word in re.findall(r'\w+', line):。此外,```` for letter in substring: if len(re.findall(letter, word)) == 0: print(word)``` 将打印任何不包含 either 的单词子字符串中的字母,而不是 所有 个。
  • 更广泛地说,这是一个很棒的正则表达式资源,您应该通过regexr.com运行您的表达式

标签: python regex string


【解决方案1】:

在这里,我们只想有一个简单的表达式,例如:

^[^bn]+$

我们在非字符类[^bn] 中添加bn 并收集所有其他字符,然后通过添加^$ 锚,我们将失败所有可能具有@987654332 的字符串@和n

Demo

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^[^bn]+$"

test_str = ("nana\n"
    "abab\n"
    "nanac\n"
    "eded")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    
    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
    
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1
        
        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.  

正则表达式

如果不需要此表达式,可以在 regex101.com 中修改/更改。

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

    【解决方案2】:

    @Xosrov 的方法是正确的,但有一些小问题和错别字。以下版本的相同逻辑有效

    import re
    
    def xstring(substring, words):
        regex = re.compile('[%s]' % ''.join(sorted(set(substring))))
        # Excluding words matching regex.pattern
        for word in words:
            if not re.search(regex, word):
                print(word)
    
    words = [
        'nana',
        'abab',
        'nanac',
        'eded',
    ]
    
    xstring("bn", words)
    

    【讨论】:

      【解决方案3】:

      如果要检查字符串是否包含一组字母,请使用括号。
      例如,使用[bn] 将匹配包含这些字母之一的单词。

      import re
      substring = "bn"
      regex = re.compile('[' + substring + ']')
      def xstring():
          with open("dename.txt") as f:
              for line in f:
                  if(re.search(regex, line) is None):
                      print(line)
      xstring()
      

      【讨论】:

      • @Wicaledon 我的错,删除 *
      • 小心使用诸如1-zone 这样的虚构示例词您可能会认为abab1-z 是一个字符范围。
      • 感谢您的回答,它运行良好。但我有一个问题。没有if(re.search(regex, line) is None):,有什么办法可以写if ...
      【解决方案4】:

      这可能不是最有效的,但是您可以尝试使用设置的交集来做一些事情,以下代码段将打印字符串 word 中的值,前提是它不包含任何字母 'b' 或 'n'

      if (not any(set(word) & set('bn'))):
              print(word)
      

      【讨论】:

        猜你喜欢
        • 2014-10-27
        • 2015-08-16
        • 1970-01-01
        • 2015-07-14
        • 1970-01-01
        • 2023-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多