python - 如何在文本文件中查找字符之前的内容

标签 python file text

我有一个文本文件,它在破折号“-”之前有一个公司名称,我想查找该公司名称示例:TELSTRA - EV 12M FWD

我只找到了访问仪表板的方法

import re
hand = open('Companies.txt')
content = hand.read()
hand.close()
for line in content:
    if re.search('  -', line) :
        print(line)

我希望输出是 TELSTRA。

最佳答案

您可以尝试在此处使用 re.findall,其模式为 (\S+)(?=\s*-):

input = "TELSTRA - EV 12M FWD"
matches = re.findall(r'(\S+)(?=\s*-)', input)
print(matches)

输出:

['TELSTRA']

关于python - 如何在文本文件中查找字符之前的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56258833/

相关文章:

python - 将模块转换为包时出错

python - kmodes VS one-hot encoding + kmeans 用于分类数据?

python - Kinect + OpenCV : Unable to fetch rotational vectors using cv2. 在 python 中解决 PnP

python - Break//在matplotlib的x轴上

file - 在脚本中通过 vim 将文件编码更改为 utf-8

c - fput 上的段错误

sql - 使用 SQL Server 2008 在本地计算机上创建文本文件

python - 如果在打开的同一行读取文件是否会自动关闭?

python - 如何将列表的每个元素保存在 .txt 文件中,每行一个?

c# - 在位图上绘制长字符串会导致绘制问题