【问题标题】:Gathering words with a set length of letters收集具有一定长度字母的单词
【发布时间】:2017-03-05 08:40:17
【问题描述】:

有没有办法在 Python 中对具有给定字母长度的单词进行分组?

我开始研究这个功能:

lenght_words(a,b,text):
returnlist = []

在返回列表中我想要有长度的单词:

a

所以我在想:

  1. 拆分文本行,以便函数在文本的不同行上运行
  2. 从行中删除标点符号
  3. 如果一行中有长度正确的单词,函数必须将它们放入返回列表中,每个单词之间有一个空格(例如'cat dog'),否则函数放入''

我知道有 splitlines() 方法,但我不知道如何使用它(即使在阅读之后)。

我想举一个函数如何工作的例子:

function(6,7,'All in the golden afternoon\nFull leisurely we glide;\nFor  both our oars, with little skill,\nBy little arms are plied.')

这个函数应该分开行:

一切都在金色的午后

我们悠闲地滑行;

对于我们的双桨,

技能不高,

小胳膊被绑在一起。

--> 删除标点并返回:

['golden','','little','little']

我知道我必须将这些词附加到返回列表中,但我不知道如何继续。

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 非常好的开始。此时,您可能应该使用defaultdict 来计算单词。词为键,计为值。使用 defaultdict 的目的是你可以为你还没有看到的单词设置一个默认值(这里是 0)。

标签: python python-3.5


【解决方案1】:

你可以这样写一个列表推导:

[token for token in s.split(" ") if a <= len(token) <= b]

它将返回变量 s (str) 中字符长度在 a (int) 和 b (int) 之间的所有单词。如何使用它的一个例子是

s = 'All in the golden afternoon\nFull leisurely we glide;'
s += '\nFor  both our oars, with little skill,\nBy little arms are plied.'
a = 6
b = 7
result = [token for token in s.split(" ") if a <= len(token) <= b]

结果将是:

['golden', 'little', 'little', 'plied.']

要去掉标点符号,只需添加

import string
s = "".join([char for char in s if char not in string.punctuation])

在最后一行之上。结果是:

['金色','小','小']

希望这对你有用!

编辑:

如果您想分别搜索不同的行,我会建议这样的解决方案:

import string


def split_by_line_and_find_words_with_length(min, max, s):
    #store result
    result = []

    # separate string lines
    lines = s.splitlines()

    for line in lines:
        # remove punctuation
        l = "".join([char for char in line if char not in string.punctuation])

        # find words with length between a and b
        find = [token for token in l.split(" ") if a <= len(token) <= b]

        # add empty string to result if no match
        if find == []: find.append("")

        # add any findings to result
        result += find

    return result

使用您的示例字符串和首选字长,这将返回 ['golden', '', 'little', 'little']。

【讨论】:

    【解决方案2】:

    当您考虑范围时,您的思路是正确的。以下是我将如何编写你的函数。

    • 创建一个具有三个参数的函数:startstop 用于范围,sentence 用于目标语句。
    • 在函数内部,创建一个名为word_list 的列表。
    • 通过.splitlines() 拆分句子,遍历句子中的每一行。
    • 从您迭代的每一行中过滤掉所有标点符号。
    • 然后,您通过列表理解遍历当前行中的每个单词,并测试您遍历的每个单词是否在给定范围内:tmp = [word for word in line.split() if start &lt;= len(word) &lt;= stop]。将列表理解的结果分配给名为 tmp 的列表。
    • 如果tmp的长度大于1
      • 用空格连接tmp 中的每个单词,并将连接的字符串添加到word_list
    • 否则,如果tmp 列表只有一个元素长
      • 只需将其添加到word_list
    • 否则为空
      • 将空字符串添加到word_list
    • 返回word_list

    使用上面的步骤,我将如何编写你的函数:

    # create a function with the parameters `start`, `stop` and `sentence`
    # `start` and `stop` are for the range, and `sentence` is the
    # target sentence to iterate over.
    def group_words_by_length(start: int, stop: int, sentence: str) -> list:
        # import the string module so we can use its punctuation attribute.
        import string
    
        # create a list to hold words that
        # are in the given `start`-`stop` range
        word_list = []
    
        # iterate over each line in the sentence
        # using the string attribute `.splitlines()`
        # which splits the string at every new line
        for line in sentence.splitlines():
    
            # filter out punctuation from
            # every line.
            line = ''.join([char for char in line if char not in string.punctuation])
    
            # iterate over every word in each line
            # via list comprehension. Inside the list comprehension
            # we only add a word if is is in the given range.
            tmp = [word for word in line.split() if start <= len(word) <= stop]
    
            # if we found more than one valid word
            # in the current line...
            if len(tmp) > 1:
    
                # join each word in the
                # list by a space, and add
                # the joined string to the `word_list`.
                tmp = ' '.join(tmp)
                word_list.append(tmp)
    
            # if we found only
            # one valid word...
            elif len(tmp) == 1:
    
                # simply add the word
                # to the `word_list`.
                word_list.extend(tmp)
    
            # otherwise...
            else:
                # add an empty string to the
                # `word_list`.
                word_list.append("")
    
        # return the `word_list`
        return word_list
    
    # testing of the function with
    # your test string.
    print(group_words_by_length(6, 7, 'All in the golden afternoon\nFull leisurely we glide;\nFor  both our oars, with little skill,\nBy little arms are plied.'))
    

    输出:

    ['golden', '', 'little', 'little']
    

    【讨论】:

    • 感谢您为我提供的帮助,输出应该是 ['golden','','little','little'] 如果没有单词与在行中找到给定的长度;所以我想我必须设置一个 if 条件才能实现它,对吧?
    • @erupti0n 对不起。你在问什么?
    • 输出应该是 ['golden','','little','little'] 但函数返回 ['golden,'little','little']
    • @erupti0n 好的,如果我提供的功能有效,请告诉我。
    • 很抱歉再次打扰您:如果在同一行上有超过 2 个具有给定长度的单词,该函数不会返回它们之间的空格,我该如何解决?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多