检查字符串是否与文件中的行完全相同

时间:2018-06-06 11:28:44

标签: python

我一直在用Python写一个倒计时程序。我写过:

#Letters Game

global vowels, consonants
from random import choice, uniform
from time import sleep
from itertools import permutations

startLetter = ""
words = []

def check(word, startLetter):
    fileName = startLetter + ".txt"
    datafile = open(fileName)
    for line in datafile:
        print("Checking if", word, "is", line.lower())
        if word == line.lower():
            return True
    return False

def generateLetters():
    lettersLeft = 9
    output = []
    while lettersLeft >= 1:
        lType = input("Vowel or consonant? (v/c)")
        sleep(uniform(0.5, 1.5))
        if lType not in ("v", "c"):
            print("Please input v or c")
            continue
        elif lType == "v":
            letter = choice(vowels)
            print("Rachel has picked an", letter)
            vowels.remove(letter)
            output.append(letter)
        elif lType == "c":
            letter = choice(consonants)
            print("Rachel has picked a", letter)
            consonants.remove(letter)
            output.append(letter)

        print("Letters so far:", output)
        lettersLeft -= 1

    return output

def possibleWords(letters, words):
    for i in range(1,9):
        print(letters)
        print(i)
        for item in permutations(letters, i):
            item = "".join(list(item))
            startLetter = list(item)[0]
            if check(item, startLetter):
                print("\n\n***Got one***\n", item)
                words.append(item)
    return words


vowels = ["a"]*15 + ["e"]*21 + ["i"]*13 + ["o"]*13+ ["u"]*5

consonants =  ["b"]*2 + ["c"]*3 + ["d"]*6 + ["f"]*2 + ["g"]*3 +["h"]*2 +["j"]*1 +["k"]*1 +["l"]*5 +["m"]*4 +["n"]*8 +["p"]*4 +["q"]*1 +["r"]*9 +["s"]*9 +["t"]*9 + ["v"]*1 +["w"]*1 +["x"]*1 +["y"]*1 +["z"]*1

print("***Let's play a letters game!***")

sleep(3)

letters = generateLetters()

sleep(uniform(1, 1.5))

print("\n\n***Let's play countdown***\n\n\n\n\n")

print(letters)

for count in reversed(range(1, 31)):
    print(count)
    sleep(1)
print("\n\nStop!")

print("All possible words:")

print(possibleWords(letters, words))

'''

#Code for sorting the dictionary into files

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet = list(alphabet)

for letter in alphabet:

    allFile = open("Dictionary.txt", "r+")

    filename = letter + ".txt"

    letterFile = open(filename, "w")

    for line in allFile:
        if len(list(line.lower())) <= 9:
            if list(line.lower())[0] == letter:
                print("Writing:", line.lower())
                letterFile.write(line.lower())

    allFile.close()
    letterFile.close()
  

我有26个文本文件,名为a.txt,b.txt,c.txt ...以使搜索更快

(对不起,它不是很整洁 - 我还没有完成它)

然而,它不是返回我期望的(pan),而是返回包含pan的所有单词(pan,pancake,panans,pandemic ......)

在Python中是否有任何方法只有在它与字符串完全相同的情况下才能返回该行?我必须先.read()文件吗?

由于

1 个答案:

答案 0 :(得分:0)

你的帖子写得很奇怪,如果我错过匹配,请原谅我

  

在Python中是否有任何方法只有在它与字符串完全相同的情况下才能返回该行?我必须先.read()文件吗?

是的,有!!!

file = open("file.txt")
content = file.read() # which is a str
lines = content.split('\n') # which is a list (containing every lines)

test_string = " pan "
positive_match = [l for l in lines if test_string in l]

这有点hacky,因为我们避免使用pan(例如)煎饼但是使用空格(然后,例如&#34; .....,pan&#34;?)。你应该看看标记化功能。作为pythonists,我们为此提供了最好的库之一:nltk

(因为,基本上,你正在重新发明轮子)