【问题标题】:Exclude \n when reading input from file [duplicate]从文件中读取输入时排除 \n [重复]
【发布时间】:2018-05-12 00:26:28
【问题描述】:

我正在尝试在废弃 twitter 时返回用户位置数据。我在使用正则表达式时遇到问题,具体来说,我希望 exclude "\n" 从输出中排除。

当前正则表达式:

data = open("user_locations.txt", "r")
valid_ex = re.compile(r'([A-Z][a-z]+), ([A-Za-z]+[^\n])')

user_locations.txt:

California, USA
You are your own ExclusiveLogo
Around The World
Galatasaray
★DM 4 PROMO / CONTENT REMOVAL★
Glasgow, Scotland
United States
Berlin, Germany
Global

预期输出:

['California, USA', 'Glasgow, Scotland', 'Berlin, Germany']

实际输出:

['California, USA\n', 'Glasgow, Scotland\n', 'Berlin, Germany\n']

预期输出与实际输出之间存在差异的另一个原因可能是我在打印列表时使用 search() 的方式。那就是:

for line in data:
    result = valid_ex.search(line)
    if result:
        locations_list.append(line)
    print(locations_list)

谢谢,任何帮助将不胜感激! :)

【问题讨论】:

  • "\n" 不是正则表达式匹配的一部分,除非您使用“DOTALL”进行多行搜索。 \n 不在正则表达式匹配中,但它在原始行中,这就是您保存的内容。你可以做line.strip()
  • 你不需要正则表达式,这只是从文件读取输入时的通用方法。
  • 好奇您看到的哪些其他答案不是解决方案? SO充满了这个问题的变种,可以追溯到十年前。如果有太多重复项,我们需要关闭一些以支持其他项。

标签: python file-io newline


【解决方案1】:

找到匹配项后,您致电locations_list.append(line)。这会追加整行(包括换行符),而不仅仅是匹配的内容。

这里有几个选项可以获得您想要的结果:

选项 1

locations_list.append(line) 更改为locations_list.append(line.strip())

选项 2

获取所需匹配的结果:

with open('test.txt') as f:
    print(re.findall(r'[A-Z][a-z]+, [A-Za-z]+', f.read()))

输出:

['California, USA', 'Glasgow, Scotland', 'Berlin, Germany']

【讨论】:

    【解决方案2】:

    您是否考虑过使用str.strip() 删除尾随的换行符?

    【讨论】:

      【解决方案3】:

      一个简单的解决方案是将所有连续的空白字符替换为一个空格。

      text = re.sub(r'\s+', ' ', text) 
      

      【讨论】:

        猜你喜欢
        • 2021-09-17
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多