查找包含字符串中除一个字母之外的所有字母的单词

时间:2014-10-22 17:28:43

标签: python regex string

首先,这是一项家庭作业(明天到期,有趣的事实)。此分配的目标是获取用户输入的字符串,然后搜索提供给我们的字典文件并打印出除了其中一个字母之外的所有字词。
我到目前为止的代码如下。我试图使用正则表达式,但似乎只适用于模式,我不希望它只找到匹配的模式,字母可以在单词的任何位置。
另一个重要说明。我不允许在这个任务中使用列表,这是我认为我遇到的最麻烦的地方。除此之外,弦的长度每次都会变化。

import re
dictionary = open('dictionary.txt','r')

def all_but_one_letter():
    user_string = input("Please enter a string of characters: ")
    print(user_string)
    line = 'begin'
    while line != "":
        line = dictionary.readline()
        line = line.rstrip()
        if re.findall(user_string, line) == 1:
            print(line)

all_but_one_letter()             

dictionary.close()

我还必须打印一条声明,说如果没有符合标准,但是现在我更关心的是让它先工作。任何帮助,或正确方向的提示将不胜感激。

4 个答案:

答案 0 :(得分:3)

使用sets

s1 = "foobar"
s2 = "fooba"
st1 = set(s1)


print(len(st1.intersection(s2)) == len(st1) - 1)
True

您应该使用with打开文件,然后只需遍历文件对象:

def all_but_one_letter():
    with open('dictionary.txt','r') as dictionary:
        user_string = input("Please enter a string of characters: ")
        for line in dictionary:
            words = line.rstrip().split() # split into individual words
            for word in words:
                st1 = set(user_string)
                if len(st1.intersection(word)) == len(st1) - 1:
                    print(word)

交叉点将找到公共字母,如果交集等于s1的集合长度,那么除了一个字母之外的所有字母都相等

In [1]: s1 = "foobar" 
In [2]: s2 = "fooba"
In [3]: st1 = set(s1)    
In [4]: len(st1.intersection(s2)) == len(st1) - 1
Out[4]: True    
In [5]: s1 = "fooba"    
In [6]: s2 = "fooba"    
In [7]: st1 = set(s1)    
In [8]: len(st1.intersection(s2)) == len(st1) - 1
Out[8]: False

答案 1 :(得分:1)

这假设没有重复的字母,例如,一个或另一个字符串包含两个“a”。如果有多次出现的字母,您将不得不找到一种方法来删除找到的每个字母(因为您不能使用列表,复制未找到新字符串的字母)。此外,dictionary.readline()将遍历文件一次并将指针放在文件的末尾,因此下次程序通过while循环时后续的readline将不会产生任何内容,因为没有任何内容从文件末尾读取。您必须使用readlines()或其他方法将数据放入列表中,以便您可以多次迭代它。此代码尚未经过测试,因此拼写错误等由您来解决。

def all_but_one_letter(dictionary):
    user_string = input("Please enter a string of characters: ")
    user_string=user_string.lower()
    print(user_string)
    found=0
    for line in dictionary:
        line = line.rstrip().lower()
        print(line) 
        if line in user_string:
            found += 1
        else:
            print("Not Found")

    if found == len(user_string)-1
        print("Success")
    else:
        print("Failure")

dictionary = open('dictionary.txt','r').readlines()
all_but_one_letter(dictionary)             

答案 2 :(得分:0)

如果您不能使用列表,则仅限于检查字典文件中的每个单词,一次一个。所以让我们写一个函数来做到这一点:

def checkWord(word, letters):
    answer = 0
    for letter in letters:
        if letter in word:
            answer += 1
    if answer == len(letters)-1:  # `word` contains all but one letter
        return True
    else:
        return False

现在我们有了这个组件,让我们编写一个函数来从用户和该字典文件中获取输入:

def main(infilepath):
    letters = input("Enter a string of letters: ")
    with open(infilepath) as infile:
        for line in infile:
            word = line.strip()
            if checkWord(word, letters):
                print(word, "has all but one letter in", letters)

答案 3 :(得分:0)

打印dictionary.txt中除给定用户字符串以外的所有字母的单词:

#!/usr/bin/env python3
def all_but_one_letter(word, letters):
    """Whether *word* contains all but one letter from *letters*."""
    return len(letters.intersection(word)) == (len(letters) - 1)

letters = frozenset(input("Please enter a string of characters: "))
with open('dictionary.txt') as file:
    for line in file:
        for word in line.split():
            if all_but_one_letter(word, letters):
                print(word)

all_but_one_letter(word, letters)的实施是suggested by @Padraic Cunningham。我修改了他的答案,修复了与代码中的小问题无关的主要问题。