Python 需要删除包含“quot;”的句子吗&引用;在文本文件中

Python 需要删除包含“quot;”的句子吗&引用;在文本文件中,python,Python,我已经编写了一个python脚本来查找文件中包含问号的句子 f = open('Inline.txt',"r") # open the file for reading lines = f.readlines() # read all the lines from it for line in lines: if re.search("^[^\n]*\?[^\n]*(?:\n|$)",line): print(line) f.close() 输出与预期一致 A

我已经编写了一个python脚本来查找文件中包含问号的句子

f = open('Inline.txt',"r")    # open the file for reading
lines = f.readlines()         # read all the lines from it
for line in lines:
 if re.search("^[^\n]*\?[^\n]*(?:\n|$)",line):
    print(line)
f.close() 
输出与预期一致

And what exactly is it you're doing which is running ahead of -- or appearing torun ahead of expectations? That would my first question.

But I wondered can you talk a little bit more in terms of any signs in shift incustomer behavior or anything that can help us out as we think about next year? And I guess the defensibility of margins in that context as wellwould be helpful.Timo J.
现在我想删除上面的行和任何少于4个单词的句子。为此,我写了下面的脚本

f = open('Inline.txt',"r")    
lines = f.readlines()         # read all the lines from it
f.close()                     # close the file

f = open('Inline.txt',"w")    


for line in lines:
  if len(line.split(' ')) >= 4 and "^[^\n]*\?[^\n]*(?:\n|$)" not in line:
      f.write(line)
f.close()

我做错了什么?少于4个单词就可以了,但是带问号的句子仍然存在。

我不知道为什么您突然将正则表达式的执行方式从第一个代码块更改为第二个代码块。如果要使用regex并检查模式是否在文件中,则必须像在第一个示例中一样使用
re.search(模式,文本)
。在第二个示例中,您正在查看文本
^[^\n]*\?[^\n]*(?:\n |$)
是否在文件中的某个位置,并且在正常文本中,该概率为零

基本上你只需要改变:

if len(line.split(' ')) >= 4 and "^[^\n]*\?[^\n]*(?:\n|$)" not in line:
致:


以下是如何实现这一目标的示例:

"""
remove lines containing: ^\n, ?, less than 4 words
"""

import re

with open('./Inline.txt', 'r') as rfd:
    for line in rfd:

        if line.startswith('\n'):
            continue

        words_pattern = re.compile(r'\w+')
        match = words_pattern.findall(line)
        if len(match) < 4:
            continue

        q_mark_pattern = re.compile(r'.+\?.+')
        if q_mark_pattern.match(line):
            continue

        print line
“”“
删除包含以下内容的行:^\n,?,少于4个字
"""
进口稀土
将open('./Inline.txt',r')作为rfd:
对于rfd中的行:
如果line.startswith('\n'):
持续
words\u pattern=re.compile(r'\w+'))
匹配=单词\u模式.findall(行)
如果长度(匹配)<4:
持续
q\u mark\u pattern=re.compile(r'.+\?.+'))
如果q_标记_模式匹配(线):
持续
打印行

正则表达式比在python中解析字符串更快:。它看起来是解决这个问题的正确方法,因为表达式模式很小。而且上述方法在空间复杂度方面也更好,因为它不会将整个文件读入内存。

您仍然需要使用正则表达式,您不能只使用
而不使用
通过使用迭代方法来实现您的目标。首先,使用正则表达式删除问号。第二,删除“少于4个单词”的东西。谢谢。我已经更新了我的代码以使用正则表达式。对于行中的行:如果重新搜索(“^[^\n]*\?[^\n]*(?:\n |$)”,行):“”否则:f.write(行)f.close()
"""
remove lines containing: ^\n, ?, less than 4 words
"""

import re

with open('./Inline.txt', 'r') as rfd:
    for line in rfd:

        if line.startswith('\n'):
            continue

        words_pattern = re.compile(r'\w+')
        match = words_pattern.findall(line)
        if len(match) < 4:
            continue

        q_mark_pattern = re.compile(r'.+\?.+')
        if q_mark_pattern.match(line):
            continue

        print line