【问题标题】:Processing a string in a user-defined function在用户定义的函数中处理字符串
【发布时间】:2020-09-20 13:28:40
【问题描述】:

我被要求通过 Python 中的用户定义函数处理给定的字符串。

目标是将字符串作为输入,然后将其拆分为单个标记的列表,删除空格,删除长度仅为 1 个字符的标记,将每个标记转换为小写,然后返回显示每个标记的字典以及该特定令牌的出现次数。

示例输入:“Hello world I am learning learning learning Python”

期望的输出:{'hello':1, 'world':1, 'i':1, 'am':1, 'learning':3, 'python':1}

我对 Python 用户定义函数非常陌生,所以我绝对可以使用我能获得的任何帮助。这是我目前的想法:

import numpy as np
import csv

def count_token(text):    
    token_count = None
   
    # split the string
    tokens = text.split(" ")

    for token in tokens:
        # remove spaces
        tokens.append(token.strip())
        #remove word if only 1 character
        if len(token) <=1:
            token.remove()
        # convert to lowercase
        token.lower()
        return tokens
    
    # create dictionary that includes a count for every token
    token_count = {tokens : tokens.count()}
    return token_count


Hello = "Hello   world I am   learning learning learning     Python"
count_token(Hello)

【问题讨论】:

    标签: python string function


    【解决方案1】:

    这应该可以解决问题:

    sentence = 'Hello I am learning learning python'
    
    def counting_tokens(var):
        dc = {}
        tokens = var.split()
    
        for i in tokens:
            if len(i) <= 1:
                tokens.remove(i)
    
        for i in range(len(tokens)):
            tokens[i] = tokens[i].lower()
    
        for item in tokens:
            dc[item] = dc.get(item, 0) + 1
    
        print(dc)
    
    counting_tokens(sentence)
    

    可能有一种更简洁的方法,而不是所有的 for 循环,但它有效。您可以使用 split 将句子拆分为一个列表,然后循环遍历列表以删除 1 个字符的单词并将大小写更改为小写。然后用字典来计算你有多少个单词。

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 2021-01-26
      • 2013-06-03
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多