273. Integer to English Words (Python)

273. Integer to English Words

Hard

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"'

 

笔记:

以三个数为一组数进行处理,最后加上Thousand, Million, and Billion.

class Solution(object):
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        num_to_English = {0:'Zero', 1:"One", 2:"Two", 3:"Three", 4:"Four", 5:"Five", 6:"Six", 7:"Seven",
                      8:"Eight", 9:"Nine", 10:'Ten', 11:"Eleven", 12:"Twelve", 13:"Thirteen", 14:"Fourteen",
                      15:"Fifteen", 16:"Sixteen", 17:"Seventeen", 18:"Eighteen", 19:"Nineteen", 20:"Twenty",
                      30:"Thirty", 40:"Forty", 50:"Fifty", 60:"Sixty", 70:"Seventy", 80:"Eighty", 90:"Ninety"}

        rlt = []
        if num == 0:
            return "Zero"
        cnt = 1
        while num > 0:
            temp = num % 1000
            digits = temp % 10
            decades = temp // 10 % 10
            hundreds = temp // 100
            two_ = temp % 100
            temp_rlt = ""
            if hundreds > 0:
                temp_rlt += num_to_English[hundreds] + " " + "Hundred"
            if decades > 0:
                if two_ > 0 and two_ <= 19:
                    if temp_rlt:
                        temp_rlt += " "
                    temp_rlt += num_to_English[two_]
                elif two_ > 19:
                    if temp_rlt:
                        temp_rlt += " "
                    temp_rlt += num_to_English[decades * 10]
                    if digits > 0:
                        temp_rlt += " " + num_to_English[digits]
            else:
                if digits > 0:
                    if temp_rlt:
                        temp_rlt += " "
                    temp_rlt += num_to_English[digits]

            if temp_rlt:
                if cnt == 2:
                    temp_rlt += " " + "Thousand"
                elif cnt == 3:
                    temp_rlt += " " + "Million"
                elif cnt == 4:
                    temp_rlt += " " + "Billion"
                rlt.append(temp_rlt)
            cnt += 1
            num //= 1000
        rlt.reverse()
        result = ""
        for i in rlt[:-1]:
            result += i + " "
        result += rlt[-1]
        #print(result)
        return result

 

### 如何使用 Python 实现生成或处理评论的功能 在 Python 中,可以利用多种方法和技术来实现与评论相关的功能。这通常涉及数据存储、自然语言处理(NLP)、文本分析以及其他高级技术。以下是几个主要方向及其具体实现方式: #### 数据存储和管理 为了保存用户的评论并对其进行操作,可以选择数据库作为基础工具。例如,SQLite 是一种轻量级的关系型数据库引擎,适合小型项目;而 MongoDB 则是一种 NoSQL 数据库,适用于更复杂的数据结构。 ```python import sqlite3 def create_comment_table(): connection = sqlite3.connect('comments.db') cursor = connection.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS comments ( id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, content TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ) """) connection.commit() connection.close() create_comment_table() ``` 上述代码创建了一个名为 `comments` 的表用于存储用户评论的信息[^1]。 #### 自然语言处理 (NLP) 对于评论的情感分析或者关键词提取等功能,则需要用到 NLP 技术。常用的库有 NLTK 和 TextBlob。这些库可以帮助识别正面/负面情绪、主题分类等。 ```python from textblob import TextBlob def analyze_sentiment(comment_text): blob = TextBlob(comment_text) sentiment_polarity = blob.sentiment.polarity if sentiment_polarity > 0: return 'Positive' elif sentiment_polarity < 0: return 'Negative' else: return 'Neutral' example_comment = "I love this product!" print(analyze_sentiment(example_comment)) # Output should be Positive ``` 此部分展示了通过简单的函数调用来判断一条给定评论的情绪倾向[^2]。 #### 文本预处理 当涉及到大量原始评论时,可能还需要执行一系列清理工作,比如去除停用词(stopwords),转换大小写等等。Pandas 库非常适合这种批量处理的任务。 ```python import pandas as pd from nltk.corpus import stopwords nltk.download('stopwords') def preprocess_comments(comments_df): stop_words = set(stopwords.words('english')) def remove_stopwords(text): words = str(text).split() filtered_sentence = [w for w in words if not w.lower() in stop_words] return " ".join(filtered_sentence) comments_df['cleaned_content'] = comments_df['content'].apply(remove_stopwords) return comments_df data = {'content': ["This is an example comment", "Another one here"]} df = pd.DataFrame(data) processed_df = preprocess_comments(df) print(processed_df) ``` 这里提供了关于如何去掉英文中的常见无意义词汇的例子。 #### 安全性和验证机制 最后,在实际应用环境中,还需考虑安全性因素——防止 SQL 注入攻击等问题的发生。可以通过参数化查询等方式增强系统的健壮性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值