Python 从文件读取输入时排除\n

Python 从文件读取输入时排除\n,python,file-io,newline,Python,File Io,Newline,我试图在废弃twitter时返回用户位置数据。我在正则表达式方面遇到了问题,具体来说,我希望从输出中排除“\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 Ga

我试图在废弃twitter时返回用户位置数据。我在正则表达式方面遇到了问题,具体来说,我希望从输出中排除“\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)

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

您是否考虑过使用删除尾随的换行符?

当您找到匹配项时,可以调用
位置\u list.append(line)
。这将附加整行(包括换行符),而不仅仅是匹配的内容

以下是获得所需结果的几个选项:

选项1

locations\u list.append(line)
更改为
locations\u 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']

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

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

“\n”不是正则表达式匹配的一部分,除非使用“DOTALL”进行多行搜索。\n不在正则表达式匹配中,但它在原始行中,这是您保存的内容。您可以执行
line.strip()
。您不需要正则表达式,而且这只是从文件中读取输入时的一般操作。好奇您看到的其他哪些答案不是解决方案?因此,这个问题的变体可以追溯到十年前。如果有太多的重复,我们需要关闭一些,以利于其他人。