附加文件中与模式匹配的文本

2024-04-26 14:41:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为文本.txt在

内容文本.txt公司名称:

1. Luv_dev
2. Amit_dev
3. Sandeep_supp
4. Prateek_supp
5. Sumit_dev
6. Shashank_dev
7. Kush_supp
8. Ritesh_dev
9. Shubham_supp
10. Ravi_dev

我需要在每个名字后面附加一个文本(我称之为概要文件的描述)。在

示例:第一行“1。Luv_nudev“I want to append”<;-He's a developer”后面,因为它包含关键字“\u dev”。在

同样,对于第三行“3。Sandeep_supp“i want append”<;—He's a support guy“在后面,因为它包含关键字“\u supp”。在

所以我希望我的文本文件是这样的:

^{pr2}$

我已经开始这么做了,但我认为我没有走上实现目标的正确轨道。在

 #!/usr/bin/python

 import re

 file = open("text.txt","a")
 for line in file:
     match_for_dev = re.match(r"\d+\.\s\w+_dev$",line)
     match_for_supp = re.match(r"\d+\.\s\w+_supp$",line)
     if match_for_dev:
          file.write("<- He's a developer")
     if match_for_supp:
          file.write("<- He's a support guy")

这个代码没有给我任何东西:(


Tags: dev文本ltretxtformatchline
0条回答
网友
1楼 · 发布于 2024-04-26 14:41:31

您的一个问题是,您试图从一个为写入而打开的文件中读取。这是不可能的。你需要从一个文件中读取,然后写入另一个文件。下面的代码使用^{}-语句打开输入文件和输出文件。在

这里不需要正则表达式。{{如果你想用cd2}来结束{或者你可以简单地用cd2}来结束。为此,请使用^{}

with open("text.txt", "r") as inp, open("out.txt", "w") as output:
   for line in inp:
       l = line.strip()
       if l.endswith("dev"):
           output.write("{} <- He's a developer\n".format(l))
       if l.endswith("supp"):
           output.write("{} <- He's a support guy\n".format(l))

你的python版本已经有六年了。您应该考虑至少更新到Python2.7.x,但最好是更新到Python3.x。必须手动打开和关闭文件:

^{pr2}$

输出到顺序文件公司名称:

msvalkon@Lunkwill:/tmp$ cat out.txt 
1. Luv_dev <- He's a developer
2. Amit_dev <- He's a developer
3. Sandeep_supp <- He's a support guy
4. Prateek_supp <- He's a support guy
5. Sumit_dev <- He's a developer
6. Shashank_dev <- He's a developer
7. Kush_supp <- He's a support guy
8. Ritesh_dev <- He's a developer
9. Shubham_supp <- He's a support guy
10. Ravi_dev <- He's a developer
msvalkon@Lunkwill:/tmp$ 
网友
2楼 · 发布于 2024-04-26 14:41:31

line.rsplit()测试

有多种方法可以测试角色,一种是bingrsplit,它以已定义的字符串为分隔符,从右侧开始拆分行,次数与next参数中指定的次数相同。在

>>> line "name_surname_role".rsplit("_", 1)
["name_surname", "role"]

我还改变了逻辑,从字典中找到完整的角色名。在

如果角色不存在,则默认使用“未知角色”。在

^{pr2}$

如果您发现Python的旧版本不知道string.format是关于什么的,请更改行

    out_f.write("{line} <- He's a {rolename}\n".format(**locals()))

进入

    out_f.write("%s <- He's a %s\n" % (line, rolename))

这也适用于最近的Python。在

网友
3楼 · 发布于 2024-04-26 14:41:31

我的代码也在工作:D

#!/usr/bin/python

import re

input = open("text.txt","r")
output = open("out.txt","w")
for line in input:
    match_for_dev = re.search(r"\d+\.\s\w+_dev$",line)
    match_for_supp = re.search(r"\d+\.\s\w+_supp$",line)
    if match_for_dev:
            output.write("%s <- He's a developer\n" % match_for_dev.group(0))
    if match_for_supp:
            output.write("%s <- He's a support guy\n" % match_for_supp.group(0))

input.close()
output.close()

感谢大家的回答:)

相关问题 更多 >