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

2024-10-01 09:27:45 发布

您现在位置: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()

I have 26 text files called a.txt, b.txt, c.txt... to make the search quicker

(对不起,不是很整齐-我还没做完)

但是,它没有返回我所期望的(pan),而是返回所有包含pan的单词(pan,pancake,pans,popularity…)

在Python中,是否有任何方法只能返回与字符串完全相同的行?我必须先.read()文件吗?你知道吗

谢谢


Tags: intxtforoutputiflinesleepitem
2条回答

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

Is there any way in Python you can only return the line if it's EXACTLY the same as the string? Do I have to .read() the file first?

是的,有!!!你知道吗

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]

这有点麻烦,因为我们避免用pancake代替pan(例如),而是使用空格(然后,像“…,pan”这样的例子呢)。您应该看看标记化函数。作为pythonists,我们拥有最好的库:nltk

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

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

Is there any way in Python you can only return the line if it's EXACTLY the same as the string? Do I have to .read() the file first?

是的,有!!!你知道吗

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]

这有点麻烦,因为我们避免用pancake代替pan(例如),而是使用空格(然后,像“…,pan”这样的例子呢)。您应该看看标记化函数。作为pythonists,我们拥有最好的库:nltk

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

相关问题 更多 >