[英]Python merging data in two files
我有兩個文本文件。 一個文本文件是“ numbers.txt”。 它包含10位數字的電話號碼,每行一個。 第二個文件“用戶”包含有關多個帳戶的數據。 我只想查找numbers.txt中列出的帳戶信息
因此,對於numbers.txt中的每個數字,搜索用戶文件以獲取該數字。 如果找到,則返回該文本行和下一行文本(或返回所有文本,直到下一個空行也將起作用)。
Numbers.txt看起來像:
1234567021
1234566792
用戶文件如下所示:
1234567021@host.com User-Password == "secret"
Framed-IP-Address = 192.168.1.100,
結果我正在尋找:
1234567021 1234567021@host.com User-Password == "secret" Framed-IP-Address = 192.168.1.100
我對如何處理感到困惑/困惑。 到目前為止,我有:
#!/usr/bin/env python
import os
# Load numbers text file
if os.path.isfile("numbers.txt"):
print "Loaded Numbers"
#### Open file, if exists
numbers = open('numbers.txt', 'r')
else:
print "ERROR: Unable to read numbers.txt"
quit()
# Load user data file
if os.path.isfile("users.txt"):
print "Loaded user data"
#### Open file, if exists
users_data = open('users.txt', 'r')
else:
print "ERROR: Unable to read users_data"
quit()
#### Search
if any(str(users_data) in s for s in numbers):
for line in numbers:
if number in line:
#### Produce sanitized list of output
output = line.split(' ')
#print output[0]
print output
# also need next line from users_data
# after each match
#### Close numbers file and quit
numbers.close()
users_data.close()
quit()
代碼不是最佳的,因此必須讀取users_datanumbers.txt行次數:
#### Search
for number in numbers:
for data in users_data:
if data.startswith(number):
print (number, data)
我只是建議您可以先對數據進行排序,然后再循環搜索數字。 可以在users_data中找到該號碼。
這是用Python 3編寫的,以獲得我想要的StringIO
的行為。
只需將with StringIO(nums_txt) as f:
更改with StringIO(nums_txt) as f:
將open('numbers.txt') as f:
更改open('numbers.txt') as f:
使用nums文件的文件名,並與用戶文件部分相同。 這應該很明顯:
nums_txt='''\
1234567021
1234566792'''
users='''
1234567021@host.com User-Password == "secret"
Framed-IP-Address = 192.168.1.100,
'''
import re
from io import StringIO
with StringIO(nums_txt) as f: # with open('numbers.txt') as f: ...
nums={line.strip():'Not Found' for line in f}
nfs={}
with StringIO(users) as f: # with open('users.txt') as f: ...
for m in re.finditer(r'(^\d{10})(@.*?)(?=(?:\d{10}@)|\Z)', f.read(), re.S | re.M):
rec=re.sub(r'\s{2,}', ' ', ' '.join(m.group(2).splitlines()))
if m.group(1) in nums:
nums[m.group(1)]=rec
else:
nfs[m.group(1)]='Not Found'
print(nums)
印刷品:
{'1234567021': '@host.com User-Password == "secret" Framed-IP-Address = 192.168.1.100,', '1234566792': 'Not Found'}
評論:
users
文件的格式是否如此並不明顯。 相應地調整正則表達式 numbers
唯一時才有效 users
沒有相應數量numbers
都聚集在字典nfs
將數字讀入一組
with open('numbers.txt') as f:
numbers = {line.strip() for line in f if line.strip()}
查看users.txt
中每行的前十個字符。 如果該字符串是numbers
,則將兩行保存到一個容器中( dict
)
result = dict()
with open('users.txt') as f:
for line in f:
key = line[:10]
if key in numbers:
value = line + f.next()
result[key] = value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.