从无组织的单词列表中组织一个用逗号分隔的单词列表(仅在可能的情况下提供提示)

Posted

技术标签:

【中文标题】从无组织的单词列表中组织一个用逗号分隔的单词列表(仅在可能的情况下提供提示)【英文标题】:Organize a List of Words Separated by Comma from Unorganized List of Words (TIPS ONLY IF POSSIBLE) 【发布时间】:2021-06-20 15:44:24 【问题描述】:

基本上,我有一长串想要使用 Python 组织的单词(如下提供)。问题是单词列表还没有逗号+它们由换行符分隔,并且大约有 200 个。退格两次并为每个单词添加一个逗号似乎有点乏味,我相信有一些方法可以在 Python 中自动执行此操作。但是,我是初学者,实在想不出方法。

如果可能的话,我正在寻找可以为我指出解决这个问题的正确方向的人,因为我真的很想自己解决这个问题(大部分情况下,哈哈)。

我希望它看起来像这样:

[Adventurous, Aggressive, Agreeable, Alert, Alive, Amused] 

(等等)


这就是我复制/粘贴单词列表的方式:

adorable

adventurous

aggressive

agreeable

alert

alive

amused

angry

annoyed

annoying

anxious

arrogant

ashamed

attractive

average

awful

bad

beautiful

better

bewildered

black

bloody

blue

blue-eyed

blushing

bored

brainy

brave

breakable

bright

busy

calm

careful

cautious

charming

cheerful

clean

clear

clever

cloudy

clumsy

colorful

combative

comfortable

concerned

condemned

confused

cooperative

courageous

crazy

creepy

crowded

cruel

curious

cute

dangerous

dark

dead

defeated

defiant

delightful

depressed

determined

different

difficult

disgusted

distinct

disturbed

dizzy

doubtful

drab

dull

【问题讨论】:

如果你使用pycharm/Notepad++,你可以只竖选文本并添加逗号 您确定所需的输出正确吗?为什么所有单词都大写,为什么不加引号?如果需要,您可以edit。顺便说一句,欢迎来到 Stack Overflow!如果需要提示,请查看tour 和How to Ask。 【参考方案1】:

您可以使用tkinter 模块从剪贴板中获取复制的文本,然后使用split 换行符上的文本\n 最后filter 任何只是一个空字符串的项目。

import tkinter as tk
root = tk.Tk()
text = root.clipboard_get()
list(filter(lambda x: x != '', text.split('\n')))

输出:

['adventurous', 'aggressive', 'agreeable', 'alert', 'alive', 'amused', 'angry', 'annoyed', 'annoying', 'anxious', 'arrogant', 'ashamed', 'attractive', 'average', 'awful', 'bad', 'beautiful', 'better', 'bewildered', 'black', 'bloody', 'blue', 'blue-eyed', 'blushing', 'bored', 'brainy', 'brave', 'breakable', 'bright', 'busy', 'calm', 'careful', 'cautious', 'charming', 'cheerful', 'clean', 'clear', 'clever', 'cloudy', 'clumsy', 'colorful', 'combative', 'comfortable', 'concerned', 'condemned', 'confused', 'cooperative', 'courageous', 'crazy', 'creepy', 'crowded', 'cruel', 'curious', 'cute', 'dangerous', 'dark', 'dead', 'defeated', 'defiant', 'delightful', 'depressed', 'determined', 'different', 'difficult', 'disgusted', 'distinct', 'disturbed', 'dizzy', 'doubtful', 'drab', 'dull']

【讨论】:

Ew,不要使用list(filter(lambda)),而是使用列表推导:[x for x in text.split('\n') if x]。您甚至不需要与空字符串进行比较,因为它是虚假的。所以实际上,你可以使用list(filter(None, text.split('\n'))),这样会更好。

以上是关于从无组织的单词列表中组织一个用逗号分隔的单词列表(仅在可能的情况下提供提示)的主要内容,如果未能解决你的问题,请参考以下文章

需要 c# 正则表达式将逗号列表中的任何单词与另一个字符串中的任何单词匹配

leetcode884. 两句话中的不常见单词

逗号分隔的列表正则表达式 [重复]

快乐水题884. 两句话中的不常见单词

将用逗号分隔的所有单词放在新行上[重复]

如何选择包含特定子字符串的单词列表作为 SQL 查询(oracle)的一部分?