2013-07-13 2 views
2

파이썬 또는 기본 셸 스크립트에서이 작업을 수행하려고합니다.목록에서 여러 행을 가진 파일을 읽는 중 변수 - 파이썬 또는 쉘

데이터를 조작하고 변수에 저장하려는 여러 항목이있는 파일이 있습니다.

파일에 여러 열이 있습니다. 첫 번째 열은 사람의 이름 (예 : 조, 메리 등)입니다. 두 번째 (쉼표 뒤)는 ID입니다. 나는 각 ID를 변수에 저장하고 다음과 같이 링크를 구성하려고합니다. 내가 변수로 "두 번째 열"의 각 값을 저장할 수있는 방법

Joe, 21142 21143 21909 24125 
Mary, 22650 23127 
John, 24325 
Mike, 24683 24684 26973 

을 나는 다음과 같은 링크를 구성 할 수 있도록 : 문제는 당신이 아래에 볼 수있는 하나 개의 이름은 단 하나 개의 ID 또는 다수를 가질 수 있다는 것입니다 :

http://example/Joe/21142 
http://example/Joe/21143 
http://example/Joe/21909 
http://example/Joe/24125 
http://example/Mary/22650 
http://example/Mary/23127 

감사합니다. 당신이 URL을 재사용하기 때문에

  • 오마르

답변

1

GNU awk

awk -F'[, ]+' '{for (i=2; i<=NF; ++i) print "http://example/"$1"/"$i }' input.txt 
http://example/Joe/21142 
http://example/Joe/21143 
http://example/Joe/21909 
http://example/Joe/24125 
http://example/Mary/22650 
http://example/Mary/23127 
http://example/John/24325 
http://example/Mike/24683 
http://example/Mike/24684 
http://example/Mike/26973 

으로 아니면 내가이 파티에 늦은 것 같아

s = '''Joe, 21142 21143 21909 24125 
Mary, 22650 23127 
John, 24325 
Mike, 24683 24684 26973 
''' 
from StringIO import StringIO 
from contextlib import closing 
with closing(StringIO(s)) as f: 
    for line in f: 
      x, y = line.split(',') 
      x = x.strip() 
      y = y.strip().split() 
      leader = 'http://example/{}'.format(x) 
      print '\n'.join('{}/{}'.format(leader, z) for z in y) 
+0

우수! 감사!!!! 이것은 큰 일했다! !! – Omar

+0

@Omar, 잘 알고 있습니다! – iruvar

0

는 재사용 가능한 템플릿을 생성하기 위해 더 나은,

myfile = open('input','r') 
link = dict() 
for line in myfile: 
    line = line.split(",") 
    IDs = line[1].split() 
    link[line[0]]=IDs 
myfile.close() 

for name in link.keys(): 
    for ID in link[name]: 
     print ''.join(["www.whatever.com/",name,"/",ID]) 
+0

잘 작동했습니다. 고맙습니다!!!! – Omar

0

첫째을보십시오. 다음으로 이름이 많은 id를 가질 수 있으므로 각 루프를 생성하기 위해 메인 루프 내에서 다른 루프를 실행해야합니다. 아래 코드가 작동해야합니다.

url_template = "http://example/%s/%d" 
with open("input.file") as f: 
    for line in f: 
     name = line.split(',')[0].strip() 
     n_ids = line.split(',')[1].strip().split(' ') 
     for n_id in nids: 
      print url_template % (name, nid) 
+0

감사합니다. "$ python test.py 트레이스 백 (가장 최근 호출 마지막) : 파일"test.py ", 2 행 open ("test.file ")을 f : IOError : [Errno 2] 그런 파일이나 디렉토리가 없습니다 : 'test.file'' – Omar

+0

이봐, 거기에 파일 이름을 넣어야 해. 파일 이름이 뭐니? 내 암호조차 이해 했니? –

0

파이썬에서 수 수행 할 수 있습니다뿐만 아니라 주 :

lines = '''Joe, 21142 21143 21909 24125 
Mary, 22650 23127 
John, 24325 
Mike, 24683 24684 26973''' 

    linesList = lines.split("\n") 
    for line in linesList: 
     lineList = line.split(",") 
     lineName = lineList[0]; 
     lineNumbers = lineList[1].split(" ") 
     for lineNumber in lineNumbers: 
      if lineNumber.isdigit(): 
       print("http://example.com/" + lineName + "/" +lineNumber) 
1

bash 응답 : 읽기 명령 ope 파일에 대해 줄무늬로 표시하고 쉼표 또는 공백으로 구분 된 단어를 배열로 가져옵니다.

while IFS=$', \t' read -ra words; do 
    for ((i=1; i<${#words[@]}; i++)); do 
     printf "http://example/%s/%s\n" "${words[0]}" "${words[i]}" 
    done 
done < file