【问题标题】:Python 3 removing puctuation from text filePython 3 从文本文件中删除波动
【发布时间】:2017-10-06 17:57:14
【问题描述】:

我是一名初级程序员,我的作业遇到了一些麻烦。所以我希望你能帮助我。我的任务如下:

用 Python 编写一个程序,在屏幕上显示从作为标准输入输入的文本文件中读取的行的最后 3 个单词。假设文本文件中的所有行至少包含三个单词。仅将至少一个字母组成的字符串视为一个单词。

这是输入文本文件:

Elizabeth it is in vain you say
"Love not"—thou sayest it in so sweet a way:
In vain those words from thee or L.E.L.
Zantippe's talents had enforced so well:
Ah! if that language from thy heart arise,
Breath it less gently forth—and veil thine eyes.
Endymion, recollect, when Luna tried
To cure his love—was cured of all beside—
His follie—pride—and passion—for he died.

这应该是输出:

vain you say 
sweet a way 
l e l 
enforced so well 
thy heart arise 
veil thine eyes 
when luna tried 
of all beside 
for he died

但是,我似乎也需要删除所有标点符号。这就是我遇到的麻烦。所以这是我的代码:

import sys

def main():

    for item in sys.stdin:
        item = item.split()[-3:]
        string = ' '.join(item)
        print (string)

main()

【问题讨论】:

标签: python


【解决方案1】:

最好的方法是s.translate(None, string.punctuation)

【讨论】:

  • 如果您需要一个替代方案,我很乐意提供一个,但没有一个能比我在效率方面提出的方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2015-07-30
相关资源
最近更新 更多