微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在用户定义的函数中处理字符串

如何解决在用户定义的函数中处理字符串

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

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

示例输入:“我正在学习世界,您正在学习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)

解决方法

这应该可以解决问题:

    static void Main(string[] args)
    {
        // -int size = Convert.ToInt32(Console.In.ReadLine());   // this to change amount of variables the user wants instead of [x]
        int[] numbers = new int[10];  //  task 1,modul 3. The 10 in the array is a statment for how many varibles this array can hold.
                                        // you can have as many varibles as you want.
        Random randomNumbers = new Random();
        int winNum = randomNumbers.Next(1,26);
        Console.WriteLine(winNum);
        Console.WriteLine("Pick your 10 numbers! "); // här får vi våra 10 tal av användaren 
        for (int hallon = 0; hallon < 10; hallon++)  //this loop will print the users numbers
        {

            Console.WriteLine($"Your have used: {hallon}"); // här får vi våra 10 tal av användaren 
            try
            {
                numbers[hallon] = Convert.ToInt32(Console.In.ReadLine());  // numbers lagrar våra 10 tal som kommer spelas nu mot winNum
            }
            catch (SystemException e) // going to catch if the user writes in a letter instead of a number        
            {
                --hallon;
                Console.WriteLine(e.Message);
            }
            if (numbers[hallon] < 1 || numbers[hallon] > 25)
            {
                Console.WriteLine("Write a number within 1-25. ");
                --hallon;
            }
        }

        if (numbers.Any(n => n == winNum))
        {
            Console.WriteLine("You won! The lucky number was:" + winNum);
        } else
        {
            Console.WriteLine("You lost");
        }

        Console.WriteLine("End of the game");
        Console.ReadLine();
    }

可能有比所有的for循环更简洁的方法,但是它可以工作。您可以使用split将句子拆分为一个列表,然后循环浏览列表以删除1个字符的单词并将大小写更改为小写。然后使用字典来计算每个单词的数量。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。