开发者

Replace a number with another number [closed]

开发者_StackOverflow It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

Consider a list of numbers:

1
2
3
17
8
9
23
...etc.

I want to replace these numbers with another number, based on another list:

1001=1
1002=2
1003=3
1004=8
1005=23
1006=9
1007=17

What is the quickest way to do this? (like using regular expression in Notepad++, etc.)


I do this kind of thing in perl -- something like

%replacements = (1=>1001, 2=>1002, 3=>1003 );
while (<>) {
   chomp;
   @nums = split(/ /);
   @outnums = ();
   foreach $n (@nums) {
       $outnums[$#outnums + 1] = $replacements{$n};
   }
   print join(' ', @outnums)."\n";
}

then run

perl scriptname.pl < infile > outfile


You don't want a regex since you need to somehow map the numbers to their replacements. Here's a script in Ruby:

Given a file called 'nums' like so:

1
2
3

...and so on...

map = {
  1 => 1000,
  2 => 2000,
  ...etc...
}
results = File.open('output','a')
File.open('nums').readlines.each do |line|
  results.write( map[line.to_i].to_s + "\n" ) if map.has_key?(line.to_i)
end

Run this like: ruby thescript.rb and the file 'output' now has your new number set.


Put your mappings into an array (or a dictionary, depending on how your numbers are, such that):

map[oldvalue] = newvalue;

Then iterate over the original list and replace, eg:

oldlist = '1\n2\n3\n17'
map = {'1' : '1001', '2': '1002', '3' : '1003', '17' : '1007'}

result = ''
for num in oldlist.split('\n'):
    result += map[num] + '\n'

See it on ideone

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜