繁体   English   中英

从Python中的文本文件中获取某些单词和短语

[英]Grab certain words and phrases from a text file in Python

我有这个代码块,它通过一个文本文件,逐行抓取它并将其分成单独的单词。 这一切都很好,但在我的文本文件中,我有一些以' - '开头并以' - '结尾的单词和短语,例如'-foo-'或'-foo bar-'。 现在,由于代码分为'-foo'和'bar-',它们被拆分了。 我理解为什么会发生这种情况。

我的计划是抓住那些以' - '开头和结尾的实例,将它们存储到一个单独的列表中,然后用户将每个短语更改为新的,将它们放回列表中。 如果它是两个单独的单词,我如何告诉它抓取某个短语?

def madLibIt(text_file):
    listOfWords = [] #creates a word list
    for eachLine in text_file: #go through eachLine, and split it into 
        #seperate words
        listOfWords.extend(eachLine.split())
 print listOfWords

在没有分隔符的情况下调用str.split()按空格分割文本,因此您不使用-作为分隔符。

您可以将re.findall()与模式(-.+?-)

matches = re.findall(r'(-.+?-)', 'This is a -string- with a -foo bar-')
print(matches) # ['-string-', '-foo bar-']

这个正则表达式正好抓住你想要的东西。

import re

s = 'This is a string with -parts like this- and -normal- parts -as well-'

print re.findall(r'((?:-\w[\w\s]*\w-)|(?:\b\w+\b))', s)

>>> 
['This', 'is', 'a', 'string', 'with', '-parts like this-', 'and', '-normal-', 'parts', '-as well-']

暂无
暂无

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

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