简体   繁体   English

从 Python 文件中选择特定单词

[英]Selecting specific words from a file in Python

I am completly new to python, and I need a specific answer.我对 python 完全陌生,我需要一个具体的答案。 I need to print only the authors name from a list of reference in a file by using python code.我只需要使用 python 代码从文件中的参考列表中打印作者姓名。

You can use a brute-horse algorithm to check if each word in the file is the last name of an author.您可以使用 brute-horse 算法来检查文件中的每个单词是否都是作者的姓氏。

bookFile = open("someBook.txt", "r"); ### replace with the actual txt file location

fullText = bookFile.read(); ### reads the text in bookFile
words = fullText.split(' '); ## an array of all of the words in the bookFile

bookFile.close();

authorLNList = [ "Rowling", "Tolkien", "Twain", "Martin" ]; ### replace with the actual reference list of authors

for word in words: ### iterates over each word in the book
    if word in authorLNList: ### if the word is the last name of an author
        print( str( word ) );

This only checks for last names of authors, but you can easily check for multi-word strings as well with a bit of editing.这仅检查作者的姓氏,但您也可以通过一些编辑轻松检查多字串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM