[英]how to find words containing specific letters in a .txt file with Python?
[英]How to Find Words Not Containing Specific Letters?
我正在嘗試使用正則表達式和我的文本文件編寫代碼。 我的文件逐行包含這些詞:
nana
abab
nanac
eded
我的目的是:顯示不包含作為子字符串字母給出的字母的單詞。
例如,如果我的子字符串是"bn"
,我的輸出應該只是eded
。 因為nana
和nanac
包含“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()
我該如何解決這個問題?
在這里,我們只想有一個簡單的表達式,例如:
^[^bn]+$
我們在非字符類[^bn]
中添加b
和n
並收集所有其他字符,然后通過添加^
和$
錨點,我們將使所有可能具有b
和n
字符串失敗。
# 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可視化正則表達式:
@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)
如果要檢查字符串是否包含一組字母,請使用方括號。
例如,使用[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()
它可能不是最有效的,但您可以嘗試使用設置交集執行某些操作,以下代碼段僅在字符串 word 中不包含任何字母 'b' 或 'n' 時才會打印該值
if (not any(set(word) & set('bn'))):
print(word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.