使用python替换字符串中的单词

使用python替换字符串中的单词,python,Python,我得到的输出是同一行,没有任何变化。但是,如果我编写'somestring'而不是'getstopwords'我的输入文件是SAMPLE.TXT,内容如下 import re fp1 = open('stopwords.txt','r') stop = fp1.readline() #print(stop) def passstopwords(getstopwords): stopword = getstopwords #print(stopword) fp = op

我得到的输出是同一行,没有任何变化。但是,如果我编写
'somestring'
而不是
'getstopwords'

我的输入文件是SAMPLE.TXT,内容如下

import re

fp1 = open('stopwords.txt','r')
stop = fp1.readline()
#print(stop)

def passstopwords(getstopwords):
    stopword = getstopwords
    #print(stopword)
    fp = open('read1.txt', 'r')
    line = fp.readline
    while line:
        line = fp.readline()
        print(getstopwords)
        line = re.sub(getstopwords, r'', line)
        print(line)
    fp.close()
    return;

passstopwords(stop)
stopwords.txt是

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap
into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets con
代码是:

Lorem
simply
book
printing
import re
fp1 = open('stopwords.txt','r')
lisOfStopWords = fp1.readlines()
fp1.close()

def passstopwords(lisOfStopWords):
    stopwords = "|".join([x.strip() for x in lisOfStopWords])
    print("Stopwords:" + stopwords)
    fp = open('SAMPLE.TXT', 'r')
    stopWordPattern = r"%(stopwords)s" % {'stopwords' : stopwords}
    for line in fp.readlines():
        print("ORIGINAL:" + line.strip())
        line = re.sub(stopWordPattern, r'', line)
        print("REPLACED:"+ line)
    fp.close()
    return;

passstopwords(lisOfStopWords)
输出为:

Lorem
simply
book
printing
import re
fp1 = open('stopwords.txt','r')
lisOfStopWords = fp1.readlines()
fp1.close()

def passstopwords(lisOfStopWords):
    stopwords = "|".join([x.strip() for x in lisOfStopWords])
    print("Stopwords:" + stopwords)
    fp = open('SAMPLE.TXT', 'r')
    stopWordPattern = r"%(stopwords)s" % {'stopwords' : stopwords}
    for line in fp.readlines():
        print("ORIGINAL:" + line.strip())
        line = re.sub(stopWordPattern, r'', line)
        print("REPLACED:"+ line)
    fp.close()
    return;

passstopwords(lisOfStopWords)

如您所见,将替换
Lorem
simply
book
printing

请更正函数的缩进。是的,请。给定的脚本没有运行,因为它没有正确缩进。另外,您使用什么输入?请使用更好的参数名称。这将使您的代码更容易理解
GetStopbowrs
感觉像是一个函数,我将调用它来获取停止词。如果它是一种模式,请使用类似于
stop\u word\u pattern
的方法。请发布一个变量getstopWordsOry的示例内容,以进行简单的编码。我正在通过变量传递字符串,我正在从另一个文件读取该变量。该文件由单词-是、和等组成。每行中只有一个单词。谢谢。但问题是,我正在通过一个名为“stopword”@nameetnamet的变量传递值。请粘贴完整的代码好吗?stopword与stopword1\n stopWord2看起来如何?它是一个文本文件,格式如下:是and,我得到了答案。我所要做的就是使用stop=stop.strip(),然后通过它。现在完全可以用了。谢谢大家。