社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中,不能删除句点''。

Rick Crespo • 7 年前 • 2173 次点击  

试图找出如何从我的输出中删除句点。作业的正确答案是:wa。EA。人工智能.六、六 我的输出是:wa。EA。人工智能。阿维。

我试过用rstrip删除。但那不起作用。

感谢您对这个新手python程序员的一些见解。

stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 
'so', 'it', 'and', 'The']
sent = "The water earth and air are vital"
s_sent=sent.split()
acro = ''
for word in s_sent:
    if word not in stopwords:
       acro=acro + str.upper(word[:2])+". "            
       acro=acro.rstrip('.')
print(acro)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43011
文章 [ 3 ]  |  最新文章 7 年前
quamrana Take_Care_
Reply   •   1 楼
quamrana Take_Care_    7 年前

这也可以缩短为:

stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']
sent = "The water earth and air are vital"

acro = '. '.join(word[:2].upper() for word in sent.split() if word not in stopwords)
print(acro)

输出:

WA. EA. AI. AR. VI

更新:

但是,正如“mad”所指出的, join 在这种情况下,希望创建一个字符串,首先是正确的长度,然后是正确的内容。但要知道正确的长度,它需要找到它要连接的所有组件的长度,因此,如果有一个列表作为其参数,则意味着它有一个大小,而我对生成器的原始答案只有在用完后才有大小。

所以,最好是:

acro = '. '.join([word[:2].upper() for word in sent.split() if word not in stopwords])
pi.
Reply   •   2 楼
pi.    7 年前

这是因为你的最后一个角色 acro 是一个空格字符。你要么 rstrip(". ") 或 rstrip(" .") .

mad_
Reply   •   3 楼
mad_    7 年前

你 join 把你自己从处理剩余空间的麻烦中解救出来 '.'

stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 
'so', 'it', 'and', 'The']
sent = "The water earth and air are vital"
s_sent=sent.split()
acro = []
for word in s_sent:
    if word not in stopwords:
       acro.append( str.upper(word[:2]))
print('. '.join(acro))

产量

WA. EA. AI. AR. VI

另一个简单的方法是引入一个标志来检查第一个值,然后巧妙地附加 '. ' 在最后一个值的末尾。这样就不会有额外的尾随字符

smart_flag = True
acro = ''
for word in s_sent:
    if word not in stopwords:
        if smart_flag:
            acro=acro+str.upper(word[:2])
            smart_flag=False
        else:
            acro=acro +". " + str.upper(word[:2])           

print(acro)

只是为了完整 acro.rstrip(' .')) 将删除你传入的任何字符。我的意思是它将删除 '' 以及 ' .'