简体   繁体   中英

Print in single line in Python

Given some code:

keyword=re.findall(r'ke\w+ = \S+',s)
score=re.findall(r'sc\w+ = \S+',s)
print '%s,%s' %(keyword,score)

The output of above code is:

['keyword = NORTH', 'keyword = GUESS', 'keyword = DRESSES', 'keyword = RALPH', 'keyword = MATERIAL'],['score = 88466', 'score = 83965', 'score = 79379', 'score = 74897', 'score = 68168']

But I want the format should be different lines like:

NORTH,88466
GUESS,83935
DRESSES,83935
RALPH,73379
MATERIAL,68168

Instead of the last line, do this instead:

>>> for k, s in zip(keyword, score):
        kw = k.partition('=')[2].strip()
        sc = s.partition('=')[2].strip()
        print '%s,%s' % (kw, sc)


NORTH,88466
GUESS,83965
DRESSES,79379
RALPH,74897
MATERIAL,68168

Here is how it works:

  • The zip brings the corresponding elements together pairwise.

  • The partition splits a string like 'keyword = NORTH' into three parts (the part before the equal sign, the equal sign itself, and the part after. The [2] keeps only the latter part.

  • The strip removes leading and trailing whitespace.

Alternatively, you can modify your regexes to do much of the work for you by using groups to capture the keywords and scores without the surrounding text:

keywords = re.findall(r'ke\w+ = (\S+)',s)
scores = re.findall(r'sc\w+ = (\S+)',s)
for keyword, score in zip(keywords, scores):
    print '%s,%s' %(keyword,score)

One way would be like would be to zip() the two lists together (to iterate over them pairwise) and use str.partition() to grab the data after the = , like this::

def after_equals(s):
    return s.partition(' = ')[-1]

for k,s in zip(keyword, score):
    print after_equals(k) + ',' + after_equals(s)

If you don't want to call after_equals() twice, you could refactor to:

for pair in zip(keyword, score):
    print ','.join(after_equals(data) for data in pair)

If you want to write to a text file (you really should have mentioned this in the question, not in your comments on my answer), then you can take this approach...

with open('output.txt', 'w+') as output:
    for pair in zip(keyword, score):
        output.write(','.join(after_equals(data) for data in pair) + '\n')

Output:

% cat output.txt
NORTH,88466
GUESS,83965
DRESSES,79379
RALPH,74897
MATERIAL,68168

Hope this will help:

keyword = ['NORTH','GUESS','DERESSES','RALPH']
score = [88466,83935,83935,73379]

for key,value in zip(keyword,score):
  print "%s,%s" %(key,value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM