【发布时间】: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)
【问题讨论】: