Python脚本在文本文件中搜索单词

Python脚本在文本文件中搜索单词,python,Python,我正在写一个Python脚本。我需要在文本文件中搜索以“s、es或ies”结尾的单词,该单词必须大于三个字母,需要知道单词的数量和单词本身…..这是一项艰巨的任务,我无法使用它,请帮助我我同意您需要进行基础工作的评论。以下是一些让你开始的想法 1) 你说“搜索一个文件”。打开一个文件,像这样逐行阅读: with open ('myFile.txt', 'r') as infile: for line in infile: # do something to each lin

我正在写一个Python脚本。我需要在文本文件中搜索以“s、es或ies”结尾的单词,该单词必须大于三个字母,需要知道单词的数量和单词本身…..这是一项艰巨的任务,我无法使用它,请帮助我

我同意您需要进行基础工作的评论。以下是一些让你开始的想法

1) 你说“搜索一个文件”。打开一个文件,像这样逐行阅读:

with open ('myFile.txt', 'r') as infile:
    for line in infile:
       # do something to each line
2) 您可能希望将每一行存储在数据结构中,如列表:

# before you open the file...
lines = []

# while handling the file:
lines.append(line)
3) 你需要处理好每一个单词。查看列表的“拆分”功能

4) 您需要查看每个单词的单个字母。查看“字符串切片”


不管怎么说,你大概可以用10-15行代码来完成这项任务。

如果感觉难以完成,试着将任务分成不同的任务。 下面的代码一点也不好,但希望它足够清晰,这样您就可以理解这一点

1首先,你需要得到你的文本。如果文本在计算机中的文件中,则需要将其放入python可以使用的文件中

# this code takes the content of "text.txt" and store it into my_text
with open("text.txt") as file:
    my_text = file.read()
现在你需要处理每个单词。您所有的单词都在一个名为my_text的字符串中,您希望将它们分隔(拆分)成一个列表,以便您可以单独使用它们。通常单词用空格分隔,所以你用空格来分隔它们:

# take the text and split it into words
my_words = my_text.split(" ")   
我不知道你到底想要什么,但假设你想把单词分别存储在不同的列表中。然后您需要这些列表:

# three list to store the words:
words_s = []
words_es = []
words_ies = []
4现在你需要反复阅读单词,并用它们做一些事情。为此,最简单的方法是使用For循环:

#iterate through each word
for word in my_words:

    # you're not interested in short words:
    if len(word) <= 3:
        continue  # this means: do nothing with this word


    # now, if the word's length is greater than 3, you classify it:

    if word.endswith("ies"):
        words_ies.append(word)   # add it to the list

    if word.endswith("es"):
        words_es.append(word)    # add it to the list

    if word.endswith("s"):
        words_s.append(word)     # add it to the list
你需要考虑的是,如果你想重复或不重复的话。请注意,条件“以“s”、“es”或“ies”结尾的单词”等同于“以“s”结尾的单词”。上面的代码将得到冗余分布在不同列表中的单词。如果一个单词以“ies”结尾,它也以“es”和“s”结尾,因此它将被存储在三个列表中。如果要避免重叠,可以用else-If语句替换If语句

继续学习其他答案所建议的基础知识,很快你就能理解像这样可怕的代码:D

with open("text.txt") as myfile:
    words = [word for word in myfile.read().split(" ") if word.endswith("s") and len(word) > 3]
    print("There are {} words ending with 's' and longer than 3".format(len(words)))

这是一个很难的任务,我不能用它工作-然后回去学习的基础知识和实际学习?要求我们为你做这件事无助于你学到任何东西。你有一个可复制的例子吗?尝试在文件的行上迭代,并使用
if
语句返回您要查找的内容。看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在海报已经试图自己解决问题时才提供帮助。展示这一成果的一个好方法是包括您迄今为止编写的代码、示例输入(如果有)、预期输出和实际获得的输出(控制台输出、回溯等)。你提供的细节越多,你可能得到的答案就越多。查看和。Python社区非常有帮助和支持,但是你必须向我们展示你至少在努力。
with open("text.txt") as myfile:
    words = [word for word in myfile.read().split(" ") if word.endswith("s") and len(word) > 3]
    print("There are {} words ending with 's' and longer than 3".format(len(words)))