首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python语言中使用随机字母从txt.file配对成单词

在Python语言中使用随机字母从txt.file配对成单词
EN

Stack Overflow用户
提问于 2021-09-06 22:27:12
回答 1查看 35关注 0票数 0

我希望通过我的任务得到一些指导,我完全是编程新手,没有任何经验。

任务:我们得到一个包含实际单词数量的txt.file,我的任务是编写一个程序,要求用户输入4-9个随机字母。让程序在txt.file中运行这些随机的字母,并找到它可以用用户输入的单词创建的所有单词。然后,它必须写出它能找到的包含用户键入的所有字母的所有单词,并按字母顺序一行打印出来。之后,它必须打印出包含用户输入的所有9个字母的单词的数量。

如果我的解释很混乱,请告诉我,我会试着为你解释得更好。我不寻找任何人来解决我的任务,我只是想要一些适当的指导,我可以做什么,以进入下一步,因为现在它只是感觉像一个死胡同。

这是我到目前为止的代码:

代码语言:javascript
复制
import os
chars = []

nine = input("Nians bokstäver: ")

lenght = len(nine)
#print(lenght) #Denna ska tas bort senare

while (lenght < 4) or (lenght > 9):
    lenght = len(nine)
    print("Fel antal, försök igen!")
    nine = input("Nians bokstäver: ")

if (lenght >= 4) and (lenght <= 9):
    lenght = len(nine)
    chars.append(nine)

file = open("/Users/************/Desktop/Programmering 1/Inlämningsuppgift/ny_svenskaord.txt", "r")

while file:
    line = file.readline()
    print(line)
    if line == "":
        break

谢谢,

艺术设计

EN

回答 1

Stack Overflow用户

发布于 2021-09-06 23:07:56

听起来你正在构建一个Anagram解算器。有几种方法可以做到这一点。由于这是一个家庭作业,我不会给出任何实际的答案,但一些路线可以查看。

pythonic式的方法是使用内置方法string.rfind(),其中string是目标文件中的一个单词。Python Docs

最健壮的方法是使用Regex查找字符和序列,但需要学习一门全新的语言。Python Docs

对于编程初学者来说,最简单的方法也是最丑陋的方法,但它使用字符串切片和循环来迭代输入中的每个字母,使用file.readline()从文件中抓取一行,然后将其拆分成字符并比较两个字符。可能看起来像这样

代码语言:javascript
复制
...
def Anagram(input, filename):

    with open(filename, 'r') as target:  # opens the file at the file path given in file name
        word = target.readline()  # reads one line of the file
        while word:  # While word is defined (has a value), loop!
            hit_list = [0]  # unfortunate naming, list of words the input compares too and a counter at index[0]
            for i in len(input):  # for letter in input
                hits = 0  # If a letter is the same as the string, add one
                '''
                Comparison code goes here
                '''
                if hits == len(word):  # if you have the same amount of hits as letters in the word its an anagram.
                    hit_list[1] = hit_list[1] + 1  # adds one to the counter
                    hit_list.append(word)  # adds the word at the end of the list
            word = target.readline()  # reads a new line from the file
    return hit_list  # returns the list you made

上面的例子有很大的漏洞和问题,但可以在非常有限的情况下工作。一些问题包括从来没有检查过输入实际上是字母,文件包含字母,文件每行使用一个单词,没有行结束字符,等等。在编写或阅读他人代码时需要考虑的事情。

祝你和Artin项目玩得开心!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69080782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档