Python multi-line code simplification

Source: Internet
Author: User

In Python, you can simplify multiple lines of code into one line, with the For loop and if condition judgments all in one line, as shown in the following example:

>>> fromNltk.corpusImportStopwords>>> english_stopwords = Stopwords.words ('中文版') #加载nltk中的英文停用词数据
#创建一个列表 with a list of 3 words>>> texts_tokenized = [['Writing','II','Rhetorical','Composing','Rhetorical','Composing'],['engages','Series','Interactive','Reading'],[' the','Composing','Activities','along','Assignments','designed',' Help']]
#用多行代码对texts_tokenized去停用词>>> text_filtered_stopwords = [[[Word forWordinchDocumentif notWordinchEnglish_stopwords] forDocumentinchTexts_tokenized]>>>text_filtered_stopwords[['Writing','II','Rhetorical','Composing','Rhetorical','Composing'], ['engages','Series','Interactive','Reading'], [' the','Composing','Activities','along','Assignments','designed',' Help']]

Then change to the general wording using multiple lines:

>>> texts_tokenized = [['Writing','II','Rhetorical','Composing','Rhetorical','Composing'],['engages','Series','Interactive','Reading'],[' the','Composing','Activities','along','Assignments','designed',' Help']]>>> documents = []>>> texts_filtered_stopwords =[]>>> forDocumentinchtexts_tokenized: forWordinchDocument:ifWord not inchenglish_stopwords:documents.append (Word) texts_filtered_stopwords.append (document)>>>texts_filtered_stopwords[['Writing','II','Rhetorical','Composing','Rhetorical','Composing'], ['engages','Series','Interactive','Reading'], [' the','Composing','Activities','along','Assignments','designed',' Help']]

You can see the same results, but the code is much more efficient and concise.

Python multi-line code simplification

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.